HackerRank - Regex - Character Class

© HackerRank

Matching Specific Characters

The character class [ ] matches only one out of several characters placed inside the square brackets.

Task

1203x.

1
^[123][120][xs0][30Aa][xsu][\.\,]$

Excluding Specific Characters

The negated character class [^] matches any character that is not in the square brackets.

Task

think?

1
^[^\d][^aeiou][^bcDF][^\s][^AEIOU][^\.\,]$

Matching Character Ranges

In the context of a regular expression (RegEx), a character class is a set of characters enclosed within square brackets that allows you to match one character in the set.

A hyphen (-) inside a character class specifies a range of characters where the left and right operands are the respective lower and upper bounds of the range. For example:

  • [a-z] is the same as [abcdefghijklmnopqrstuvwxyz]
  • [A-Z] is the same as [ABCDEFGHIJKLMNOPQRSTUVWXYZ]
  • [0-9] is the same as [0123456789]

In addition, if you use a caret (^) as the first character inside a character class, it will match anything that is not in that range. For example, [^0-9] matches any character that is not a digit in the inclusive range from 0 to 9.

It’s important to note that, when used outside of (immediately preceding) a character or character class, the caret matches the first character in the string against that character or set of characters.

Task

h4CkR

1
^[a-z][1-9][^a-z][^A-Z][A-Z]*

Resources

Regex - Subdomains - Character Class

If—

by Rudyard Kipling

If you can keep your head when all about you
Are losing theirs and blaming it on you;
If you can trust yourself when all men doubt you,
But make allowance for their doubting too;
If you can wait and not be tired by waiting,
Or, being lied about, don’t deal in lies,
Or being hated, don’t give way to hating,
And yet don’t look too good, nor talk too wise;

If you can dream—and not make dreams your master;
If you can think—and not make thoughts your aim;
If you can meet with Triumph and Disaster
And treat those two impostors just the same;
If you can bear to hear the truth you’ve spoken
Twisted by knaves to make a trap for fools,
Or watch the things you gave your life to, broken,
And stoop and build ’em up with worn-out tools;

If you can make one heap of all your winnings
And risk it on one turn of pitch-and-toss,
And lose, and start again at your beginnings
And never breathe a word about your loss;
If you can force your heart and nerve and sinew
To serve your turn long after they are gone,
And so hold on when there is nothing in you
Except the Will which says to them: “Hold on!”

If you can talk with crowds and keep your virtue,
Or walk with kings—nor lose the common touch,
If neither foes nor loving friends can hurt you,
If all men count with you, but none too much;
If you can fill the unforgiving minute
With sixty seconds’ worth of distance run,
Yours is the Earth and everything that’s in it,
And—which is more—you’ll be a Man, my son!


  • In a poll conducted in 1995 by the BBC Radio 4 Bookworm programme to determine the nation’s favourite poems, If— came first.
  • The poem If of Kipling is written as if a father is talking to his son, giving him advices on the way to behave to obtain the reputation of being a mature and an outstanding citizen of the community and the world. It has been written in 1895 and published in his collection Rewards and Fairies in 1909. Throughout the poem, Kipling illustrates ideal behaviour and virtue through the use of paradox: righteousness without smugness; detachment while practicing determination; and noble life blended with commonality. The employment of these contradictory extremes throughout the poem serves to illustrate a central theme of striving for an idealized “golden mean” in all facets of life.

Resources

HackerRank - Regex - Introduction

© HackerRank

Matching Anything But a Newline

The dot (.) matches anything (except for a newline).

Task

123.456.abc.def

1
^(.{3}\.){3}.{3}$

Matching Digits & Non-Digit Characters

\d

The expression \d matches any digit [0-9].

\D

The expression \D matches any character that is not a digit.

Task

06-11-2015

1
(\d){2}(\D){1}(\d){2}(\D){1}(\d){4}

Matching Whitespace & Non-Whitespace Character

\s

\s matches any whitespace character [ \r\n\t\f ].

\S

\S matches any non-white space character.

For Example

match blank line

1
\r\n

Task

12 11 15

1
(\S){2}(\s){1}(\S){2}(\s){1}(\S){2}

Matching Word & Non-Word Character

\w

The expression \w will match any word character.
Word characters include alphanumeric characters (a-z, A-Z and 0-9) and underscores (_).

\W

\W matches any non-word character.
Non-word characters include characters other than alphanumeric characters (a-z, A-Z and 0-9) and underscore (_).

Task

www.hackerrank.com

1
(\w){3}(\W){1}(\w){10}(\W){1}(\w){3}

Matching Start & End

^

The ^ symbol matches the position at the start of a string.

$

The $ symbol matches the position at the end of a string.

Task

0qwer.

1
^(\d){1}(\w){4}(\.){1}$

Resources

Regex - Subdomains - Introduction

LeetCode - Algorithms - 128. Longest Consecutive Sequence

Hard problem. Exercise for union-find. Almost done by myself, with help of union-find by Robert Sedgewick and Kevin Wayne.

Problem

128. Longest Consecutive Sequence

Java

union–find

© 1.5 Case Study: Union-Find Copyright © 2000–2019 Robert Sedgewick and Kevin Wayne. All rights reserved.

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
class Solution {
public int longestConsecutive(int[] nums) {
int[] arr = removeDuplicates(nums);
int N = arr.length;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0; i<N; i++) {
if (!map.containsKey(arr[i]-1)) map.put(arr[i]-1, i);
if (!map.containsKey(arr[i]+1)) map.put(arr[i]+1, i);
}
int len = 0;
UF uf = new UF(N);
for(int i=0; i<N; i++) {
if (map.containsKey(arr[i])) {
uf.union(i, map.get(arr[i]));
}
}
int[] parent = uf.parent();
Map<Integer,Integer> tmpMap = new HashMap<Integer, Integer>();
int k;
for(int i=0; i<parent.length; i++) {
k = parent[i];
if (tmpMap.containsKey(parent[i]))
tmpMap.put(k, tmpMap.get(k)+1);
else
tmpMap.put(k, 1);
}
for(Integer n : tmpMap.values()) {
if (n>len)
len = n;
}

return len;
}

private int[] removeDuplicates(int[] input) {
if (input == null || input.length <= 0) {
return input;
}
Set<Integer> aSet = new HashSet<>(input.length);
for (int i : input) {
aSet.add(i);
}
int[] a = new int[aSet.size()];
int i=0;
for(Integer x : aSet)
a[i++] = x;
return a;
}
}

/**
* Weighted quick-union by rank with path compression by halving.
* @author Robert Sedgewick
* @author Kevin Wayne
* Algorithms, 4th edition textbook code and libraries
* https://github.com/kevin-wayne/algs4
*/
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));
}
}

public int[] parent() {return parent;}
}

Submission Detail

  • 68 / 68 test cases passed.
  • Runtime: 8 ms, faster than 23.72% of Java online submissions for Longest Consecutive Sequence.
  • Memory Usage: 40.8 MB, less than 8.62% of Java online submissions for Longest Consecutive Sequence.

Resources

Some Differences between British and American English

England and America are two countries divided by a common language. — George Bernard Shaw

vocabulary

American English British English
airplane aeroplane
anyplace, anywhere anywhere
apartment flat, apartment
area code dialing code (phone)
attorney, lawyer barrister, solicitor, lawyer
bar pub
billfold wallet
busy engaged (phone)
cab taxi
call collect reverse the charges (phone)
can tin, can
candy sweets
cellphone mobile
check/bill bill (in a restaurant)
coin-purse purse
cookie, cracker biscuit
corn sweet corn, maize
crib cot
crazy mad
crosswalk pedestrian, zebra crossing
cuffs turn-ups (on trousers)
diaper nappy
doctor’s office doctor’s surgery
drugstore chemist
dumb, stupid stupid
elevator lift
eraser rubber, eraser
fall, autumn autumn
faucet, tap tap (indoors)
first floor, second floor etc ground floor, first floor etc
flashlight torch
flat (tire) flat tyre, puncture
french fries chips
garbage, trash rubbish
garbage can, trashcan dustbin, rubbish bin
gas(oline) Petrol
gear shift gear lever (on a car)
highway, freeway main road, motorway
hood bonnet (of a car, at the front)
intersection crossroads
mad angry
mail post
mean nasty
movie, film film
movies cinema
one-way (ticket) single (ticket)
pants, trousers trousers
parking lot car park
pavement road surface
pitcher jug
pocketbook, purse, handbag handbag
(potato) chips crisps
railroad railway
raise rise (in salary)
rest room, bathroom (public) toilet
resume cv
round trip return (journey / ticket)
schedule, timetable timetable
shorts pants
sidewalk pavement
sneakers trainers (=sports shoes)
spigot, faucet tap (outdoors)
stand in line queue
stingy mean (opposite of generous)
store, shop shop
subway underground, tube (train)
truck van, lorry
trunk boot (of a car, at the back)
two weeks fortnight, two weeks
undershirt vest
vacation holiday(s)
windshield windscreen (on a car)
zee zed (the name of the letter z)
zip code postcode
zipper zip

spelling

American English British English
center centre
analyze analyse
tire tyre(on a wheel)
neighbor neighbour

Resources

  • Practical English Usage, by Michael Swan
  • Learning English as a Foreign Language FOR DUMmIES, By Gavin Dudeney and Nicky Hockly

LeetCode - Algorithms - 48. Rotate Image

Done by myself. Aha following step with 867. Transpose Matrix. After I solved it, I found this In-place rotate matrix by 90 degrees in clock-wise direction on web. Interesting. It is likely to be an elegant solution to this problem. “There is no algorithm for creativity.”, as Andy Hargreaves had ever said.

Problem

48. Rotate Image

Java

1

transpose and then swap columns symmetrically

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public void rotate(int[][] matrix) {
int N = matrix.length;
int tmp;
for(int i=0; i<N; i++) {
for(int j=0; j<i; j++) {
tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
for(int i=0; i<N; i++) {
for(int j=0; j<N/2; j++) {
tmp = matrix[i][j];
matrix[i][j] = matrix[i][N-1-j];
matrix[i][N-1-j] = tmp;
}
}
}
}

Submission Detail

  • 21 / 21 test cases passed.
  • Runtime: 0 ms, faster than 100.00% of Java online submissions for Rotate Image.
  • Memory Usage: 39.4 MB, less than 5.77% of Java online submissions for Rotate Image.

2

solution of www.geeksforgeeks.org

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public void rotate(int[][] matrix) {
int N = matrix.length;
int tmp;
for(int i=0; i<N/2; i++) {
for(int j=i; j<N-i-1; j++) {
tmp = matrix[i][j];
matrix[i][j] = matrix[N-1-j][i];
matrix[N-1-j][i] = matrix[N-1-i][N-1-j];
matrix[N-1-i][N-1-j] = matrix[j][N-1-i];
matrix[j][N-1-i] = tmp;
}
}
}
}

Submission Detail

  • 21 / 21 test cases passed.
  • Runtime: 0 ms, faster than 100.00% of Java online submissions for Rotate Image.
  • Memory Usage: 39.4 MB, less than 5.77% of Java online submissions for Rotate Image.

non in-place method

matrix rotate

1
2
3
4
5
6
7
8
9
10
public int[][] rotate_math_stackexchange(int[][] matrix) {
int N = matrix.length;
int[][] R = new int[N][N];
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
R[i][j] = matrix[N-1-j][i];
}
}
return R;
}

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = function(matrix) {
var n = matrix.length;
var tmp;
for(var i=0; i<n; i++) {
for(var j=0; j<i; j++) {
tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
for(var i=0; i<n; i++) {
for(var j=0; j<n/2; j++) {
tmp = matrix[i][j];
matrix[i][j] = matrix[i][n-1-j];
matrix[i][n-1-j] = tmp;
}
}
};

Submission Detail

  • 21 / 21 test cases passed.
  • Runtime: 56 ms, faster than 57.20% of JavaScript online submissions for Rotate Image.
  • Memory Usage: 33.4 MB, less than 100.00% of JavaScript online submissions for Rotate Image.

Algorithms Quotes

An algorithm must be seen to be believed. — Donald Knuth

For me, great algorithms are the poetry of computation. Just like verse, they can be terse, allusive, dense, and even mysterious. But once unlocked, they cast a brilliant new light on some aspect of computing. — Francis Sullivan

I will, in fact, claim that the difference between a bad programmer and a good one is whether he considers his code or his data structures more important. Bad programmers worry about the code. Good programmers worry about data structures and their relationships.
Linus Torvalds

Algorithms + Data Structures = Programs. — Niklaus Wirth

Fancy algorithms are slow when N is small, and N is usually small. — Rob Pike

An algorithm is like a recipe. — Muhammad Waseem

The Euclidean algorithm is the granddaddy of all algorithms, because it is the oldest nontrivial algorithm that has survived to the present day. — Donald Knuth

The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. — Donald Knuth

Stay hungry. Stay foolish.

I am honored to be with you today for your commencement from one of the finest universities in the world. Truth be told, I never graduated from college. And this is the closest I’ve ever gotten to a college graduation. Today I want to tell you three stories from my life. That’s it. No big deal. Just three stories.

The first story is about connecting the dots.

I dropped out of Reed College after the first 6 months, but then stayed around as a drop-in for another 18 months or so before I really quit. So why did I drop out?

It started before I was born. My biological mother was a young, unwed graduate student, and she decided to put me up for adoption. She felt very strongly that I should be adopted by college graduates, so everything was all set for me to be adopted at birth by a lawyer and his wife. Except that when I popped out they decided at the last minute that they really wanted a girl. So my parents, who were on a waiting list, got a call in the middle of the night asking: “We have an unexpected baby boy; do you want him?” They said: “Of course.” My biological mother found out later that my mother had never graduated from college and that my father had never graduated from high school. She refused to sign the final adoption papers. She only relented a few months later when my parents promised that I would go to college. This was the start in my life.

And 17 years later I did go to college. But I naively chose a college that was almost as expensive as Stanford, and all of my working-class parents’ savings were being spent on my college tuition. After six months, I couldn”t see the value in it. I had no idea what I wanted to do with my life and no idea how college was going to help me figure it out. And here I was spending all of the money my parents had saved their entire life. So I decided to drop out and trust that it would all work out OK. It was pretty scary at the time, but looking back it was one of the best decisions I ever made. The minute I dropped out I could stop taking the required classes that didn’t interest me, and begin dropping in on the ones that looked interesting.

It wasn’t all romantic. I didn’t have a dorm room, so I slept on the floor in friends’ rooms, I returned Coke bottles for the 5¢ deposits to buy food with, and I would walk the 7 miles across town every Sunday night to get one good meal a week at the Hare Krishna temple. I loved it. And much of what I stumbled into by following my curiosity and intuition turned out to be priceless later on. Let me give you one example:

Reed College at that time offered perhaps the best calligraphy instruction in the country. Throughout the campus every poster, every label on every drawer, was beautifully hand calligraphed. Because I had dropped out and didn’t have to take the normal classes, I decided to take a calligraphy class to learn how to do this. I learned about serif and sans serif typefaces, about varying the amount of space between different letter combinations, about what makes great typography great. It was beautiful, historical, artistically subtle in a way that science can’t capture, and I found it fascinating.

None of this had even a hope of any practical application in my life. But 10 years later, when we were designing the first Macintosh computer, it all came back to me. And we designed it all into the Mac. It was the first computer with beautiful typography. If I had never dropped in on that single course in college, the Mac would have never had multiple typefaces or proportionally spaced fonts. And since Windows just copied the Mac, it’s likely that no personal computer would have them. If I had never dropped out, I would have never dropped in on this calligraphy class, and personal computers might not have the wonderful typography that they do. Of course it was impossible to connect the dots looking forward when I was in college. But it was very, very clear looking backward 10 years later.

Again, you can’t connect the dots looking forward; you can only connect them looking backward. So you have to trust that the dots will somehow connect in your future. You have to trust in something — your gut, destiny, life, karma, whatever. Beleiveing that the dots will connect down the road will give you the confidence to follow your heart, Even when it leads you off the well worn path, and that will make all the difference.

My second story is about love and loss.

I was lucky — I found what I loved to do early in life. Woz and I started Apple in my parents’ garage when I was 20. We worked hard, and in 10 years Apple had grown from just the two of us in a garage into a $2 billion company with over 4,000 employees. We had just released our finest creation — the Macintosh — a year earlier, and I had just turned 30. And then I got fired. How can you get fired from a company you started? Well, as Apple grew we hired someone who I thought was very talented to run the company with me, and for the first year or so things went well. But then our visions of the future began to diverge and eventually we had a falling out. When we did, our Board of Directors sided with him. So at 30 I was out. And very publicly out. What had been the focus of my entire adult life was gone, and it was devastating.

I really didn’t know what to do for a few months. I felt that I had let the previous generation of entrepreneurs down — that I had dropped the baton as it was being passed to me. I met with David Packard and Bob Noyce and tried to apologize for screwing up so badly. I was a very public failure, and I even thought about running away from the valley. But something slowly began to dawn on me — I still loved what I did. The turn of events at Apple had not changed that one bit. I had been rejected, but I was still in love. And so I decided to start over.

I didn’t see it then, but it turned out that getting fired from Apple was the best thing that could have ever happened to me. The heaviness of being successful was replaced by the lightness of being a beginner again, less sure about everything. It freed me to enter one of the most creative periods of my life.

During the next five years, I started a company named NeXT, another company named Pixar, and fell in love with an amazing woman who would become my wife. Pixar went on to create the world’s first computer animated feature film, Toy Story, and is now the most successful animation studio in the world. In a remarkable turn of events, Apple bought NeXT, I returned to Apple, and the technology we developed at NeXT is at the heart of Apple’s current renaissance. And Laurene and I have a wonderful family together.

I’m pretty sure none of this would have happened if I hadn’t been fired from Apple. It was awful tasting medicine, but I guess the patient needed it. Sometimes life hits you in the head with a brick. Don’t lose faith. I’m convinced that the only thing that kept me going was that I loved what I did. You’ve got to find what you love. And that is as true for your work as it is for your lovers. Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work. And the only way to do great work is to love what you do. If you haven’t found it yet, keep looking. Don’t settle. As with all matters of the heart, you’ll know when you find it. And, like any great relationship, it just gets better and better as the years roll on. So keep looking until you find it. Don’t settle.

My third story is about death.

When I was 17, I read a quote that went something like: “If you live each day as if it was your last, someday you’ll most certainly be right.” It made an impression on me, and since then, for the past 33 years, I have looked in the mirror every morning and asked myself: “**If today were the last day of my life, would I want to do what I am about to do today?**” And whenever the answer has been “No” for too many days in a row, I know I need to change something.

Remembering that I’ll be dead soon is the most important tool I’ve ever encountered to help me make the big choices in life. Because almost everything — all external expectations, all pride, all fear of embarrassment or failure — these things just fall away in the face of death, leaving only what is truly important. Remembering that you are going to die is the best way I know to avoid the trap of thinking you have something to lose. You are already naked. There is no reason not to follow your heart.

About a year ago I was diagnosed with cancer. I had a scan at 7:30 in the morning, and it clearly showed a tumor on my pancreas. I didn’t even know what a pancreas was. The doctors told me this was almost certainly a type of cancer that is incurable, and that I should expect to live no longer than three to six months. My doctor advised me to go home and get my affairs in order, which is doctor’s code for prepare to die. It means to try to tell your kids everything you thought you’d have the next 10 years to tell them in just a few months. It means to make sure everything is buttoned up so that it will be as easy as possible for your family. It means to say your goodbyes.

I lived with that diagnosis all day. Later that evening I had a biopsy, where they stuck an endoscope down my throat, through my stomach and into my intestines, put a needle into my pancreas and got a few cells from the tumor. I was sedated, but my wife, who was there, told me that when they viewed the cells under a microscope the doctors started crying because it turned out to be a very rare form of pancreatic cancer that is curable with surgery. I had the surgery and thankfully I’m fine now.

This was the closest I’ve been to facing death, and I hope it’s the closest I get for a few more decades. Having lived through it, I can now say this to you with a bit more certainty than when death was a useful but purely intellectual concept:

No one wants to die. Even people who want to go to heaven don’t want to die to get there. And yet death is the destination we all share. No one has ever escaped it. And that is as it should be, because Death is very likely the single best invention of Life. It is Life’s change agent. It clears out the old to make way for the new. Right now the new is you, but someday not too long from now, you will gradually become the old and be cleared away. Sorry to be so dramatic, but it is quite true.

Your time is limited, so don’t waste it living someone else’s life. Don’t be trapped by dogma — which is living with the results of other people’s thinking. Don’t let the noise of others’ opinions drown out your own inner voice. And most important, have the courage to follow your heart and intuition. They somehow already know what you truly want to become. Everything else is secondary.

When I was young, there was an amazing publication called The Whole Earth Catalog, which was one of the bibles of my generation. It was created by a fellow named Stewart Brand not far from here in Menlo Park, and he brought it to life with his poetic touch. This was in the late 1960s, before personal computers and desktop publishing, so it was all made with typewriters, scissors and polaroid cameras. It was sort of like Google in paperback form, 35 years before Google came along: It was idealistic, and overflowing with neat tools and great notions.

Stewart and his team put out several issues of The Whole Earth Catalog, and then when it had run its course, they put out a final issue. It was the mid-1970s, and I was your age. On the back cover of their final issue was a photograph of an early morning country road, the kind you might find yourself hitchhiking on if you were so adventurous. Beneath it were the words: “**Stay Hungry. Stay Foolish.**” It was their farewell message as they signed off. Stay Hungry. Stay Foolish. And I have always wished that for myself. And now, as you graduate to begin anew, I wish that for you.

Stay Hungry. Stay Foolish.

Thank you all very much.


How to Grow Old

by Bertrand Russell

In spite of the title, this article will really be on how not to grow old, which, at my time of life, is a much more important subject. My first advice would be to choose your ancestors carefully. Although both my parents died young, I have done well in this respect as regards my other ancestors. My maternal grandfather, it is true, was cut off in the flower of his youth at the age of sixty-seven, but my other three grandparents all lived to be over eighty. Of remoter ancestors I can only discover one who did not live to a great age, and he died of a disease which is now rare, namely, having his head cut off. A great-grandmother of mine, who was a friend of Gibbon, lived to the age of ninety-two, and to her last day remained a terror to all her descendants. My maternal grandmother, after having nine children who survived, one who died in infancy, and many miscarriages, as soon as she became a widow devoted herself to women’s higher education. She was one of the founders of Girton College, and worked hard at opening the medical profession to women. She used to tell of how she met in Italy an elderly gentleman who was looking very sad. She asked him why he was so melancholy and he said that he had just parted from his two grandchildren. ‘Good gracious,’ she exclaimed, ‘I have seventy-two grandchildren, and if I were sad each time I parted from one of them, I should have a miserable existence!’ ‘Madre snaturale!,’ he replied. But speaking as one of the seventy-two, I prefer her recipe. After the age of eighty she found she had some difficulty in getting to sleep, so she habitually spent the hours from midnight to 3 a.m. in reading popular science. I do not believe that she ever had time to notice that she was growing old. This, I think, is the proper recipe for remaining young. If you have wide and keen interests and activities in which you can still be effective, you will have no reason to think about the merely statistical fact of the number of years you have already lived, still less of the probable shortness of your future.

As regards health, I have nothing useful to say as I have little experience of illness. I eat and drink whatever I like, and sleep when I cannot keep awake. I never do anything whatever on the ground that it is good for health, though in actual fact the things I like doing are mostly wholesome.

Psychologically there are two dangers to be guarded against in old age. One of these is undue absorption in the past. It does not do to live in memories, in regrets for the good old days, or in sadness about friends who are dead. One’s thoughts must be directed to the future, and to things about which there is something to be done. This is not always easy; one’s own past is a gradually increasing weight. It is easy to think to oneself that one’s emotions used to be more vivid than they are, and one’s mind more keen. If this is true it should be forgotten, and if it is forgotten it will probably not be true.

The other thing to be avoided is clinging to youth in the hope of sucking vigour from its vitality. When your children are grown up they want to live their own lives, and if you continue to be as interested in them as you were when they were young, you are likely to become a burden to them, unless they are unusually callous. I do not mean that one should be without interest in them, but one’s interest should be contemplative and, if possible, philanthropic, but not unduly emotional. Animals become indifferent to their young as soon as their young can look after themselves, but human beings, owing to the length of infancy, find this difficult.

I think that a successful old age is easiest for those who have strong impersonal interests involving appropriate activities. It is in this sphere that long experience is really fruitful, and it is in this sphere that the wisdom born of experience can be exercised without being oppressive. It is no use telling grownup children not to make mistakes, both because they will not believe you, and because mistakes are an essential part of education. But if you are one of those who are incapable of impersonal interests, you may find that your life will be empty unless you concern yourself with your children and grandchildren. In that case you must realise that while you can still render them material services, such as making them an allowance or knitting them jumpers, you must not expect that they will enjoy your company.

Some old people are oppressed by the fear of death. In the young there is a justification for this feeling. Young men who have reason to fear that they will be killed in battle may justifiably feel bitter in the thought that they have been cheated of the best things that life has to offer. But in an old man who has known human joys and sorrows, and has achieved whatever work it was in him to do, the fear of death is somewhat abject and ignoble. The best way to overcome it - so at least it seems to me - is to make your interests gradually wider and more impersonal, until bit by bit the walls of the ego recede, and your life becomes increasingly merged in the universal life. An individual human existence should be like a river: small at first, narrowly contained within its banks, and rushing passionately past rocks and over waterfalls. Gradually the river grows wider, the banks recede, the waters flow more quietly, and in the end, without any visible break, they become merged in the sea, and painlessly lose their individual being. The man who, in old age, can see his life in this way, will not suffer from the fear of death, since the things he cares for will continue. And if, with the decay of vitality, weariness increases, the thought of rest will not be unwelcome. I should wish to die while still at work, knowing that others will carry on what I can no longer do and content in the thought that what was possible has been done.


Portraits from Memory


The last paragraph was selected as Lesson 11 How to grow old in New Concept English Book 4: Fluency in English by Louis George Alexander

What, according to the author, is the best way to overcome the fear of death as you get older?