No man is an island

by John Donne

No man is an island,
entire of itself;
every man is a piece of the continent,
a part of the main.
If a clod be washed away by the sea,
Europe is the less,
as well as if a promontory were.
as well as if a manor of thy friend’s
or of thine own were.
Any man’s death diminishes me,
because I am involved in mankind;
and therefore never send to know for whom the bell tolls;
it tolls for thee.


Devotions upon Emergent Occasions

Donne’s original spelling and punctuation

No man is an Iland, intire of it selfe; every man is a peece of the Continent, a part of the maine; if a Clod bee washed away by the Sea, Europe is the lesse, as well as if a Promontorie were, as well as if a Mannor of thy friends or of thine owne were; any mans death diminishes me, because I am involved in Mankinde; And therefore never send to know for whom the bell tolls; It tolls for thee.

Postgres Cheatsheet

commands

psql

psql -U user -d db -h 127.0.0.1 -p 5432

SET CLIENT_ENCODING TO 'utf8';

  • \q: quit more and return back psql
  • \l:List of databases
  • \c: connect to database
  • \d: list all database objects
  • \d tbname: view table structure
  • \d+ tbname: view table structure
  • \dt: list all tables, such as \dt public.*
  • \ds: list all sequences
  • \i xxx.sql: excute sql from file

psql import sql file

psql -h 127.0.0.1 -p 5432 -d dbname -U user -f sqlfilewithfullpath

psql uxerp < sqlfilewithfullpath

pg_dump

pg_dump -d database_name -t table_name -U username > dumpfile_with_fullpath.sql

pg_ctl

start PostgreSQL servie: pg_ctl -D “D:\data\pg11” start

stop PostgreSQL service: pg_ctl -D “D:\data\pg11” stop

view tcp port of pg service

netstat -aon|findstr “5432”

tasklist|findstr “pid”

ddl

foreign key

1

1
fk_id INTEGER REFERENCES main_tb(id),

2

1
2
fk_id INTEGER,
FOREIGN KEY (fk_id) REFERENCES main_tb (id)

sequence

When creating a new table, the sequence can be created through the SERIAL pseudo-type as follows:

1
2
3
CREATE TABLE table_name(
id SERIAL
);

LeetCode - Algorithms - 969. Pancake Sorting

Just mark it. I can’t understand the solution of leetcode.
It is NP-hard problem. Bill Gates had a paper on this topic.

Problem

煎饼排序

969. Pancake Sorting

Java

LeetCode Solution

Approach 1: Sort Largest to Smallest

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public List<Integer> pancakeSort(int[] A) {
List<Integer> ans = new ArrayList<Integer>();
int N = A.length;

Integer[] B = new Integer[N];
for (int i = 0; i < N; ++i)
B[i] = i+1;
Arrays.sort(B, (i, j) -> A[j-1] - A[i-1]);

for (int i: B) {
for (int f: ans)
if (i <= f)
i = f+1 - i;
ans.add(i);
ans.add(N--);
}

return ans;
}
}

Submission Detail

  • 215 / 215 test cases passed.
  • Runtime: 6 ms, faster than 6.90% of Java online submissions for Pancake Sorting.
  • Memory Usage: 42.8 MB, less than 5.26% of Java online submissions for Pancake Sorting.

Rosetta Code

To my surprise, the solution of Rosetta Code Sorting algorithms/Pancake sort can’t pass on leetcode.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
* Sorting algorithms/Pancake sort
* https://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
*/
public class PancakeSortRosetta {
int[] heap;

public String toString() {
String info = "";
for (int x : heap)
info += x + " ";
return info;
}

public void flip(int n, List<Integer> list) {
for (int i = 0; i < (n + 1) / 2; ++i) {
int tmp = heap[i];
heap[i] = heap[n - i];
heap[n - i] = tmp;
}
list.add(n);
System.out.println("flip(0.." + n + "): " + toString());
}

public int[] minmax(int n) {
int xm, xM;
xm = xM = heap[0];
int posm = 0, posM = 0;

for (int i = 1; i < n; ++i) {
if (heap[i] < xm) {
xm = heap[i];
posm = i;
} else if (heap[i] > xM) {
xM = heap[i];
posM = i;
}
}
return new int[] { posm, posM };
}

public void sort(int n, int dir, List<Integer> list) {
if (n == 0)
return;

int[] mM = minmax(n);
int bestXPos = mM[dir];
int altXPos = mM[1 - dir];
boolean flipped = false;

if (bestXPos == n - 1) {
--n;
} else if (bestXPos == 0) {
flip(n - 1, list);
--n;
} else if (altXPos == n - 1) {
dir = 1 - dir;
--n;
flipped = true;
} else {
flip(bestXPos, list);
}
sort(n, dir, list);

if (flipped) {
flip(n, list);
}
}

public List<Integer> pancakeSort(int[] A) {
List<Integer> list = new ArrayList<Integer>();
heap = A;
sort(A.length, 1, list);
return list;
}

public static void main(String[] args) {
int[] arr = {3, 2, 4, 1};
PancakeSortRosetta pancakesort = new PancakeSortRosetta();
List<Integer> list = pancakesort.pancakeSort(arr);
System.out.println("["+list.stream().map(Object::toString).collect(Collectors.joining(","))+"]");
Stream.of(pancakesort.heap).map(Arrays::toString).forEach(System.out::println);
}
}

ref

道德經(老子) - The Way and its Power(Lao Tzu)

Western philosophers like Aristotle and Kant are great, as they are also natural scientists. Among all philosophers, I admire René Descartes, Blaise Pascal, and Leibniz, who are also eminent mathematicians. It’s a pity that no Chinese philosopher is a mathematician. But ancient Chinese philosophers are great writers, such as Lao Tzu.
Lin Yutang featured Lao Tzu as the world’s first philosopher of camouflage. Lao Tzu is very humorous, he is also a complete pacifist.

上篇《道經》 Book I. The principles of Tao

第一章 1. On the Absolute Tao

道可道,非常道。名可名,非常名。
無,名天地之始;有,名萬物之母。
故常無,欲以觀其妙;常有,欲以觀其徼。
此兩者,同出而異名,同謂之玄。玄之又玄,眾妙之門。

The Tao the can be told of
Is not the Absolute Tao;
The Names that can be given
Are not Absolute Names.

The Nameless is the origin of Heaven and Earth;
The Named is the Mother of All Things.

Therefore:
Oftentimes, one strips oneself of passion
In order to see the Secret of Life;
Oftentimes, one regards life with passion,
In order to see its manifest forms.

These two (the Secret and its manifestations)
Are (in their nature) the same;
They are given different names
When they become manifest.

They may both be called the Cosmic Mystery:
Reaching from the Mystery into the Deeper Mystery
Is the Gate to the Secret of All Life.

If this book can be said to have a message, it is that one should to learn to think abstractly; because by doing so many philosophical difficulties simply disappear. – Mathematics: A Very Short Introduction, by Timothy Gowers

第八章 8. Water

上善若水。水善利万物而不争,处众人之所恶,故几于道。

The best of men is like water;
Water benefits all things
And does not compete with them.
It dwells in (the lowly) places that all disdain -
Wherein it comes near to the Tao.

If we take Tao as the abstract group in abstract algebra, then water likes the matrix which is the representation of the abstract group. Water is essential to all living things. By weight, the average human adult male is approximately 60% water, and the average adult female is approximately 55% water.

第十章 10. Embracing the One

专气致柔,能如婴儿乎?

In controlling your vital force to achieve gentleness,
Can you become like the new-born child?

Flexibility is a key index of vitality, which is what yoga and gymnastics are after.

第十三章 13. Praise and Blame

吾所以有大患者,为吾有身,及吾无身,吾有何患?

We have fears because we have a self.
When we do not regard that self as self,
What have we to fear?

We are born to love life. The human body is a delicate holographic universe.

Every day countless people die, and yet those who remain live as if they were immortals.
I think of death as akin to a well-earned rest. The sister of sleep, Bach calls it, in his marvelous cantata BWV 56.
Our fear of death seems to me to be an error of evolution.
– The Order of Time, by Carlo Rovelli

第十四章 14. Prehistoric Origins

绳绳不可名,复归于无物。是谓无状之状,无物之象,是谓惚恍。

Unceasing, continuous,
It cannot be defined,
And reverts again to the realm of nothingness.

That is why it is called the Form of the Formless,
The Image of Nothingness.

Although ambiguous it is, it is likely to describe something like wave-particle duality in quantum mechanics or something when language is hard to explain the unknown meaning of nature.

第二十二章 22. Futility of Contention

少则得,多则惑。

To be in want is to possess.
To have plenty is to be confused.

When we face information overload today, this catchphrase is very true for me.

第二十五章 25. The Four Eternal Models

有物混成,先天地生。
寂兮寥兮,独立而不改,周行而不殆,可以为天地母。
吾不知其名,强字之曰道

Before the Heaven and Earth existed
There was something nebulous:
Silent, isolated,
Standing alone, changing not,
Eternally revolving without fail,
Worthy to be the Mother of All Things.
I do not know its name
And address it as Tao.

A big source of the world? sounds like a poem.

第二十八章 28. Keeping to the Female

复归于婴儿

And returns again to the (innocence of the) babe.

复归于朴

And returns again to the natural integrity of uncarved wood.

Humans lose innocence due to gain of knowledge? the fall?

Over time, naturally, you lose your innocence from gaining knowledge. You can’t be innocent forever, but there’s something in innocence you need to regain to be creative. – Albert Hammond Jr.

第二十九章 29. Warning Against Interference

天下神器不可为也。
为者败之,执者失之。

(For) the world is God’s own Vessel
It cannot be made (by human interference).
He who makes it spoils it.
He who holds it loses it.

去甚,去奢,去泰

eschews excess, eschews extravagance, Eschews pride.

This following of Tao should be, in Emersonian terms, a natural flow of goodness without conscious effort. – Lin Yutang

第三十章 30. Warning Against the Use of Force

师之所处,荆棘生焉。大军之后,必有凶年。

Where armies are, thorns and brambles grow.
The raising of a great host
Is followed by a year of dearth.

Where there is war, there are pains.

第三十一章 31. Weapons of Evil

兵者不祥之器,非君子之器。不得已而用之,恬淡为上,胜而不美。而美之者,是乐杀人。夫乐杀人者,则不可得志于天下矣。

Soldiers are weapons of evil.
They are not the weapons of the gentleman.
When the use of soldiers cannot be helped,
The best policy is calm restraint.

Even in victory, there is no beauty,
And who calls it beautiful
Is one who delights in slaughter.
He who delights in slaughter
Will not succeed in his ambition to rule the world.

杀人之众,以悲哀泣之,战胜以丧礼处之。

The slaying of multitudes should be mourned with sorrow.
A victory should be celebrated with the Funeral Rite.

Nuclear weapons and Adolf Hitler are footnotes of these truths.

第三十三章 33. Knowing Oneself

知人者智,自知者明。

He who knows others is learned;
He who knows himself is wise.

知足者富

He who is contented is rich.

死而不亡者寿。

He who dies yet (his power) remains has long life.

I think genius like Bach, Mozart, Beethoven, Chopin, Galois, Riemann, etc, are immortal.

下篇《德经》 Book 2. The application of Tao

第四十章 40. The Principle of Reversion

天下万物生于有,有生于无。

The things of this world come from Being,
And Being (comes) from Non-being.

Cunning. It from bit, as John Archibald Wheeler once said. It from qubit, as Edward Witten, reinterpreted it.

第四十一章 41. Qualities of the Taoist

上士闻道,勤而行之。中士闻道,若存若亡。下士闻道,大笑之。不笑不足以为道。

When the highest type of men hear the Tao (truth),
they try hard to live in accordance with it.
When the mediocre type hear the Tao,
they seem to be aware and yet unaware of it.
When the lowest type hear the Tao,
They break into loud laughter -
If it were not laughed at, it would not be Tao.

大方无隅,大器晚成,大音希声,大象无形。道隐无名。

Great space has no corners;
Great talent takes long to mature;
Great music is faintly heard;
Great form has no contour;
And Tao is hidden without a name.

Attitude is a little thing that makes a big difference. – Winston Churchill

第四十二章 42. The Violent Man

万物负阴而抱阳,冲气以为和

The created universe carries the yin at its back
and the yang in front;
Through the union of the pervading principles it
reaches harmony.

Yin-Yang. Tai Chi. Eastern thought? Bounded rationality?

第四十四章 44. Be Content

甚爱必大费;多藏必厚亡。
故知足不辱,知止不殆,可以长久。

Therefore: he who loves most spends most,
He who hoards much loses much.
The contented man meets no disgrace;
Who know when to stop runs into no danger -
He can long endure.

第四十六章 46. Racing Horses

祸莫大于不知足;咎莫大于欲得。故知足之足,常足矣。

There is no greater curse than the lack of contentment.
No greater sin than the desire for possession.
Therefore he who is contented with contentment
shall be always content.

第四十八章 48. Conquering the World by Inaction

为学日益,为道日损。

The student of knowledge (aims at) learning day by day;
The student of Tao (aims at) losing day by day.

第五十章 50. The Preserving of Life

出生入死。生之徒,十有三;死之徒,十有三;人之生,动之于死地,亦十有三。

Out of life, death enters.
The companions (organs) of life are thirty percent;
The companions (organs) of death are (also) thirty percent.
What send man to death in this life are also (these) thirty percent.

第五十三章 53. Brigandage

大道甚夷,而人好径。

the Main path is easy to walk on,
Yet people love the small by-paths.

第五十四章 54. The Individual and the State

修之于身,其德乃真;

Cultivated in the individual, character will become genuine;

第五十五章 55. The Character of the Child

含德之厚,比于赤子。毒虫不螫,猛兽不据,玃鸟不搏。骨弱筋柔而握固。未知牝牡之合而全作,精之至也。终日号而不嗄,和之至也。

Who is rich in character
Is like a child.
No poisonous insects sting him,
No wild beasts attack him,
And no birds of prey pounce upon him.
His bones are soft, his sinews tender, yet his grip is strong.
Not knowing the union of male and female, yet his organs are complete,
Which means his vigor is unspoiled.
Crying the whole day, yet his voice never runs hoarse,
Which means his (natural) harmony is perfect.

第五十七章 57. The Art of Government

天下多忌讳,而民弥贫

The more prohibitions there are,
The poorer the people become.

第五十八章 58. Lazy Government

祸兮,福之所倚;福兮,祸之所伏。

Disaster is the avenue of fortune,
(And) fortune is the concealment for disaster.

第六十二章 62. The Good Man’s Treasure

道者万物之奥。善人之宝,不善人之所保。

Tao is the mysterious secret of the universe,
The good man’s treasure,
And the bad man’s refuge.

第六十三章 63. Difficult and Easy

图难于其易,为大于其细。天下难事必作于易,天下大事必作于细。

Deal with the difficult while yet it is easy;
Deal with the big while yet it is small.
The difficult (problems) of the world
Must be dealt with while they are yet easy;
The great (problems) of the world
Must be dealt with while they are yet small.

夫轻诺必寡信,多易必多难。

He who lightly makes a promise
Will find it often hard to keep his faith.
He who makes light of many things
Will encounter many difficulties.

第六十四章 64. Beginning and End

合抱之木,生于毫末;九层之台,起于累土;千里之行,始于足下。

A tree with a full span’s girth begins from a tiny sprout;
A nine-storied terrace begins with a clod of earth.
A journey of a thousand li beings at one’s feet.

民之从事,常于几成而败之。慎终如始,则无败事

The affairs of men are often spoiled within an ace of completion.
By being careful at the end as at the beginning
Failure is averted.

第六十七章 67. The Three Treasures

我有三宝,持而保之。一曰慈,二曰俭,三曰不敢为天下先。
慈故能勇;俭故能广;不敢为天下先,故能成器长。

I have Three Treasures;
Guard them and keep them safe:
the first is Love.
The second is, Never too much.
The third is, Never be the first in the world.
Through Love, one has no fear;
Through not doing too much, one has amplitude
(of reserve power);
Through not presuming to be the first in the world,
One can develop one’s talent and let it mature.

第六十九章 69. Camouflage

祸莫大于轻敌,轻敌几丧吾宝。

There is no greater catastrophe than to underestimate the enemy.
To underestimate the enemy might entail the loss of my treasures.

第七十三章 73. On Punishment (2)

天网恢恢,疏而不失。

The heaven’s net is broad and wide.
With big meshes, yet letting nothing slip through.

What works instead is thinking about the world as a network of events. – Part 2: the world without time, chapter 6: the world is made of events, not things, The Order of Time, by Carlo Rovelli

第七十四章 74. On Punishment (3)

民不畏死,奈何以死惧之?

The people are not afraid of death;
Why threaten them with death?

第七十五章 75. Punishment (4)

民之饥,以其上食税之多,是以饥。

When people are hungry,
It is because their rulers eat too much tax-grain.

第七十六章 76. Hard and Soft

人之生也柔弱,其死也坚强。
草木之生也柔脆,其死也枯槁。
故坚强者死之徒,柔弱者生之徒。

When man is born, he is tender and weak;
At death, he is hard and stiff.
When the things and plants are alive, they are soft
and supple;
When they are dead, they are brittle and dry.
Therefore hardness and stiffness are the companions of death,
And softness and gentleness are the companions of life.

第七十七章 77. Bending the Bow

天之道,损有馀而补不足。人之道,则不然,损不足以奉有馀。

It is the way of Heaven to take away from those that have too much
And give to those that have not enough.
Not so with man’s way:
He takes from those that have not
And gives it as tribute to those that have too much.

Balance and harmonious.
Winner-take-all. Matthew effect. The rich get richer and the poor get poorer.

第七十九章 79. Peace Settlements

天道无亲,常与善人。

But “the way of Heaven is impartial;
It sides only with the good man.”

A good heart conquers ill fortune.


The Tao Te Ching by Lao Tzu Translated by Lin Yutang, 1948

The Year

by Ella Wheeler Wilcox

What can be said in New Year rhymes,
That’s not been said a thousand times?

The new years come, the old years go,
We know we dream, we dream we know.

We rise up laughing with the light,
We lie down weeping with the night.

We hug the world until it stings,
We curse it then and sigh for wings.

We live, we love, we woo, we wed,
We wreathe our brides, we sheet our dead.

We laugh, we weep, we hope, we fear,
And that’s the burden of the year.


LeetCode - Algorithms - 200. Number of Islands

Whenever possible, steal code.
Keep it simple, stupid.
Programming Pearls, Jon Bentley.

Problem

200. Number of Islands

Given a 2d grid map of ‘1’s (land) and ‘0’s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Java

BFS

1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.LinkedList;
import java.util.Queue;

class Solution {
public int numIslands(char[][] grid) {
int h = grid.length;
if (h == 0)
return 0;
int w = grid[0].length;
int r = 0;

boolean[][] visited = new boolean[h][w];
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
visited[i][j] = false;
}
}

Queue<Integer[]> queue = new LinkedList<>();
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (!visited[i][j] && grid[i][j] == '1') {
queue.add(new Integer[]{i,j});
BFS(queue, grid, visited);
r++;
}
}
}

return r;
}

public void BFS(Queue<Integer[]> queue, char[][] islandGrid, boolean[][] visited) {

int H = islandGrid.length;
int L = islandGrid[0].length;

while (queue.isEmpty() == false) {

Integer[] x = queue.remove();
int row = x[0];
int col = x[1];

if(row<0 || col<0 || row>=H || col>=L || visited[row][col] || islandGrid[row][col]!='1')
continue;

visited[row][col]=true;
queue.add(new Integer[]{row, (col-1)});
queue.add(new Integer[]{row, (col+1)});
queue.add(new Integer[]{(row-1), col});
queue.add(new Integer[]{(row+1), col});
}
}
}

Submission Detail

  • 47 / 47 test cases passed.
  • Runtime: 10 ms, faster than 5.88% of Java online submissions for Number of Islands.
  • Memory Usage: 41.6 MB, less than 55.82% of Java online submissions for Number of Islands.

2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class Solution {
final static int d[][] = {
{0,1},
{1,0},
{0,-1},
{-1,0}
};

public int numIslands(char[][] grid) {
int h = grid.length;
if (h == 0)
return 0;
int w = grid[0].length;

int r = 0;

boolean[][] visited = new boolean[h][w];

for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
visited[i][j] = false;
}
}

Queue<Point> queue = new LinkedList<>();

for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (!visited[i][j] && grid[i][j] == '1') {
queue.add(new Point(i,j));
bfs(queue, grid, visited);
r++;
}
}
}

return r;
}

public void bfs(Queue<Point> queue, char[][] islandGrid, boolean[][] visited) {

int h = islandGrid.length;
int w = islandGrid[0].length;

while (queue.isEmpty() == false) {
Point curr = queue.poll();
int row = curr.x;
int col = curr.y;
if (isValid(islandGrid, visited, h, w, row, col)) {
visited[row][col]=true;
for (int i = 0; i < 4; i++) {
int x = curr.x + d[i][0];
int y = curr.y + d[i][1];
queue.add(new Point(x, y));
}
}
}
}

private boolean isValid(char[][] grid, boolean[][] visited, int width, int height, int row, int col) {
return (row >= 0) && (row < width) && (col >= 0) && (col < height) && grid[row][col] == '1' && !visited[row][col];
}

class Point {
int x;
int y;

public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
}

Submission Detail

  • 47 / 47 test cases passed.
  • Runtime: 5 ms, faster than 15.24% of Java online submissions for Number of Islands.
  • Memory Usage: 42.3 MB, less than 17.21% of Java online submissions for Number of Islands.

union–find

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
class Solution {
final static int d[][] = {
{0,1},
{1,0},
{0,-1},
{-1,0}
};

public int numIslands(char[][] grid) {
int h = grid.length;
if (h == 0)
return 0;
int w = grid[0].length;

int N = 0;
List<Point> ptlist = new ArrayList<Point>();
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (grid[i][j] == '1') {
Point pt = new Point(i,j);
ptlist.add(pt);
map.put(i+","+j, N++);
}
}
}

UF uf = new UF(N);
for (int i = 0; i < N; i++) {
Point curr = ptlist.get(i);
int row = curr.x;
int col = curr.y;
for (int k = 0; k < 4; k++) {
int x = row + d[k][0];
int y = col + d[k][1];
if (isValid(grid, h, w, x, y)) {
uf.union(i, map.get(x + "," + y));
}
}
}

return uf.count();
}


private boolean isValid(char[][] grid, int width, int height, int row, int col) {
return (row >= 0) && (row < width) && (col >= 0) && (col < height) && grid[row][col] == '1';
}

class Point {
int x;
int y;

public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
}

class UF {
private int[] parent;
private byte[] rank;
private int count;

public UF(int n) {
if (n < 0) throw new IllegalArgumentException();
count = n;
parent = new int[n];
rank = new byte[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}

public int find(int p) {
validate(p);
while (p != parent[p]) {
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}

public int count() {
return count;
}

public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;

if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
else {
parent[rootQ] = rootP;
rank[rootP]++;
}
count--;
}

private void validate(int p) {
int n = parent.length;
if (p < 0 || p >= n) {
throw new IllegalArgumentException("index " + p + " is not between 0 and " + (n-1));
}
}
}

Submission Detail

  • 47 / 47 test cases passed.
  • Runtime: 28 ms, faster than 5.05% of Java online submissions for Number of Islands.
  • Memory Usage: 45.3 MB, less than 5.12% of Java online submissions for Number of Islands.

ref

Chapter 8 - The Majesty of Light - From Pagan to Christian - Lin Yutang

The world of Jesus is the world of sunlight by comparison with that of all the sages and philosophers and the schoolmen of any country. Like the Jungfrau which stands above the glaciers in the world of snow and seems to touch heaven itself, Jesus’ teachings have that immediacy and clarity and simplicity which puts to shame all other efforts of men’s minds to know God or to inquire after God.

Whence came this dazzling light of Jesus, which put Him in a special category by Himself among all teachers of men? Whence came the “prepossessing” power of Jesus, as Emerson called it?

Quite apart from the content of Jesus’ teachings, I think the light and the power (dazzling light always has power) of Jesus came from the manner and the voice of His teaching and from His personal example. Jesus spoke as no teacher of men ever spoke. Jesus never expounded His faith, never reasoned it out. He spoke with the simplicity and certainty of clear knowledge.

Thus it is that the world of Jesus contains both that power, and something else—the absolute clarity of light, without the self-limitation of Confucius, the intellectual analysis of Buddha, or the mysticism of Chuangtse. Where others reasoned, Jesus taught, and where others taught, Jesus commanded. He spoke out of the fullness of the knowledge and love of God. Jesus communicated the feeling of the immediate knowledge and love of God, and further, immediately and without qualification, equated that love of God with obeying His commandment, which is to love one another. If all great truths are simple, we stand here in the presence of a simple truth which contains the germ of the principle for all human development, and is sufficient.

Laotse and Jesus are brothers in spirit. Jesus said, “I am meek and lowly,” and Laotse said, “Hold on to meekness and the lowly position.”

Jesus has no dogmas, no creeds, no rites, and no rituals. Jesus taught a principle, or rather two principles in one: that the kingdom of God is within you, and, almost in the same breath, that the meek and the humble shall inherit the earth. The first teaches the inner freedom of man’s spirit; the second, the worthiness of the “least of these my brethren.” In other words, the humblest man is free in spirit, and the humblest man shall win. These are the spiritual principles behind all freedom and all democracy.

This sublime person, who each day still presides over the destiny of the world, we may call divine, not in the sense that Jesus has absorbed all the divine, or has been adequate to it (to employ an expression of the schoolmen), but in the sense that Jesus is the one who has caused his fellow-men to make the greatest step toward the divine. Mankind in its totality offers an assemblage of low beings, selfish, and superior to the animal only in that its selfishness is more reflective. From the midst of this uniform mediocrity, there are pillars that rise toward the sky, and bear witness to a nobler destiny. Jesus is the highest of these pillars which show to man whence he comes, and whither he ought to tend. In him was condensed all that is good and elevated in our nature. . . .

But whatever may be the unexpected phenomena of the future, Jesus will not be surpassed. His worship will constantly renew its youth, the tale of his life will cause ceaseless tears, his sufferings will soften the best hearts; all the ages will proclaim that, among the sons of men, there is none born who is greater than Jesus.
– Renan

Who but a Frenchman with the delicacy and depth of the French could express it so well and so eloquently?

In actual fact, Christianity in China never made converts by doctrines, but it did make converts whenever a Chinese came into personal contact with a Christian personality who followed the Christian teachings; namely, those few words “Love ye one another.”

Christians breed Christians, but Christian theology does not.

Maxim(至理名言)

事实上我们全都是些集体性人物,不管我们愿意把自己摆在什么位置,严格地说,可以看成我们所特有的东西是微乎其微的,就像我们个人是微乎其微的一样。我们全都要从前辈或同辈那里学习到一些东西,就连最大的天才,如果单凭他所具有的内在的自我去对付一切,他也决不会有多大成就。我们的发展要归功于广大世界千丝万缕的影响,从这些影响中,我们吸收我们能吸收的和对我们有用的那一部分。(歌德)

But, in fact, we are all collective beings, let us place ourselves as we may. For how little have we, and are we, that we can strictly call our own property? We must all receive and learn both from those who were before us, and from those who are with us. Even the greatest genius would not go far if he tried to own everything to his own internal self.

I by no means owe my works to my own wisdom alone, but to a thousand things and persons around me, who provided me with material. There were fools and sages, minds enlightened and narrow, childhood, youth, and mature age - all told me what they felt, what they thought, how they lived and worked, and what experiences they had gained; and I had nothing further to do than to put out my hand and reap what others had sown for me.

— Johann Wolfgang von Goethe, Goethe’s Works


任何个人要想突然做出惊人的发现 ,这是不符合事物发展的规律的 。科学是一步一个脚印地向前发展 ,每个人都要依赖前人的工作 。当你听说一个突然的 ,意想不到的发现 ——仿佛晴天霹雳时 ,你永远可以确信 ,它总是由一个人对另一个人的影响所导致的 ,正是因为有这种相互影响才使科学的进展存在着巨大的可能性 。科学并不依赖于某一个人的思想 ,而是依赖于千万人的集体智慧 ,千万人思考着同一个问题 ,每一个人尽他自己的一份力量 ,知识的大厦就是这样建造起来的 。(卢瑟福)

It is not in the nature of things for any one man to make a sudden violent discovery; science goes step by step, and every man depends on the work of his predecessors. When you hear of a sudden unexpected discovery—a bolt from the blue, as it were—you can always be sure that it has grown up by the influence of one man on another, and it is this mutual influence which makes the enormous possibility of scientific advance. Scientists are not dependent on the ideas of a single man, but on the combined wisdom of thousands of men, all thinking of the same problem, and each doing his little bit to add to the great structure of knowledge which is gradually being erected.
— Ernest Rutherford


我曾经为知识领域添瓦加砖,也曾帮别人添枝加叶;这些东西的价值,比起身后留下某种纪念物的大数学家或任何其他大大小小的艺术家们创造的价值,只是程度上有所不同,性质上并无差异。(哈代)

The case for my life, then, or for that of any one else who has been a mathematician in the same sense which I have been one, is this: that I have added something to knowledge, and helped others to add more; and that these somethings have a value which differs in degree only, and not in kind, from that of the creations of the great mathematicians, or of any of the other artists, great or small, who have left some kind of memorial behind them.
– A Mathematician’s Apology, G. H. Hardy


每个人都是混账、坏蛋,只有耶稣基督除外。爱因斯坦也是个坏蛋,因为在原子弹被引爆之后,他并没有离开美国,尽管他曾极力反对使用原子弹。
最终,通过事物之间的普遍联系,一个人会以这样或那样的方式,在深浅不等的程度上与世界上发生的所有事物都扯上干系。如果一个人可以对任何一个事件施加任何影响,那么他就要为此承担责任。(亚历山德罗夫)

Everyone is a bastard, everyone is bad, with the possible exception of Jesus Christ. Einstein is bad too, because he did not leave America after the nuclear bomb was detonated over his objections.In the end, through the general interconnectedness of events, a person becomes, in some way or another, to a greater or lesser extent, party to everything that happens in the world, and if he can exert any influence whatsoever on any event, then he becomes responsible for it.
– Aleksandr Danilovich Aleksandrov

How Terence Tao learn Javascript and gamify logic

QED - an interactive textbook


Terence Tao

Terence Tao is a starlike mathematician of our time. he is also a geek mathematician.


Repository for the QED interactive text and possible extensions
https://github.com/teorth/QED


Gamifying propositional logic: QED, an interactive textbook

It took a while for me to come up with a workable game-like graphical interface for all of this, but I finally managed to set one up, now using Javascript instead of Scratch (which would be hopelessly inadequate for this task); indeed, part of the motivation of this project was to finally learn how to program in Javascript, which turned out to be not as formidable as I had feared (certainly having experience with other C-like languages like C++, Java, or lua, as well as some prior knowledge of HTML, was very helpful).

QED version 2.0: an interactive text in first-order logic

I feel though that there could be more that could be done with this sort of framework (e.g., improved GUI, modification to other logics, developing the ability to write one’s own texts and libraries, exploring mathematical theories such as Peano arithmetic, etc.). But writing this text (particularly the first-order logic sections) has brought me close to the limit of my programming ability, as the number of bugs introduced with each new feature implemented has begun to grow at an alarming rate. I would like to repackage the code so that it can be re-used by more adept programmers for further possible applications, though I have never done something like this before and would appreciate advice on how to do so.

LeetCode - Algorithms - 210. Course Schedule II

only when I combined two man’s solutions did it pass on Leetcode.

Problem

210. Course Schedule II

topological sort of DAG.

Java

DFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
int[] tp = new int[numCourses];

List<Edge> edges = new ArrayList<Edge>();
for(int i=0; i<prerequisites.length; i++) {
edges.add(new Edge(prerequisites[i][0],prerequisites[i][1]));
}
Graph graph = new Graph(edges, numCourses);

if (!isDAG(graph, numCourses))
return new int[]{};

List<Integer> tplist = new ArrayList<Integer>();
Stack<Integer> stack = new Stack<Integer>();

boolean visited[] = new boolean[numCourses];
for (int i = 0; i < numCourses; i++)
visited[i] = false;

for (int i = 0; i < numCourses; i++)
if (visited[i] == false)
topologicalSortUtil(i, visited, stack, graph);
while (stack.empty() == false)
tplist.add( stack.pop() );

Collections.reverse(tplist);
for(int i=0; i<tplist.size();i++)
tp[i] = tplist.get(i);

return tp;
}

void topologicalSortUtil(int v, boolean visited[], Stack<Integer> stack, Graph graph) {
visited[v] = true;
Integer i;
Iterator<Integer> it = graph.adjList.get(v).iterator();
while (it.hasNext()) {
i = it.next();
if (!visited[i])
topologicalSortUtil(i, visited, stack, graph);
}
stack.push(new Integer(v));
}

public boolean isDAG(Graph graph, int N) {
boolean[] discovered = new boolean[N];

int[] departure = new int[N];

int time = 0;

for (int i = 0; i < N; i++)
if (discovered[i] == false)
time = DFS(graph, i, discovered, departure, time);

for (int u = 0; u < N; u++) {
for (int v : graph.adjList.get(u)) {
if (departure[u] <= departure[v])
return false;
}
}

return true;
}

private int DFS(Graph graph, int v, boolean[] discovered, int[] departure, int time) {
discovered[v] = true;

for (int u : graph.adjList.get(v)) {
if (!discovered[u])
time = DFS(graph, u, discovered, departure, time);
}

departure[v] = time++;

return time;
}
}

class Edge {
int source, dest;

public Edge(int source, int dest) {
this.source = source;
this.dest = dest;
}

}

public class Graph {
List<List<Integer>> adjList = null;

Graph(List<Edge> edges, int N) {
adjList = new ArrayList<>(N);

for (int i = 0; i < N; i++) {
adjList.add(i, new ArrayList<>());
}

for (Edge edge : edges) {
adjList.get(edge.source).add(edge.dest);
}
}

}

Submission Detail

  • 44 / 44 test cases passed.
  • Runtime: 9 ms, faster than 37.80% of Java online submissions for Course Schedule II.
  • Memory Usage: 39.7 MB, less than 98.78% of Java online submissions for Course Schedule II.

ref