added alternative approach with matrix multiplication; refactoring