How to programmatically find out which version of Magento 2 is installed?

Magento 2.3 has removed its version information from the composer.json files since 2018-04-05.

I have updated my Magento version detection code for compatibility with Magento 2.3: