Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tetris-ing an array

Consider the following array:

/www/htdocs/1/sites/lib/abcdedd /www/htdocs/1/sites/conf/xyz /www/htdocs/1/sites/conf/abc/def /www/htdocs/1/sites/htdocs/xyz /www/htdocs/1/sites/lib2/abcdedd 

what is the shortest and most elegant way of detecting the common base path - in this case

/www/htdocs/1/sites/ 

and removing it from all elements in the array?

lib/abcdedd conf/xyz conf/abc/def htdocs/xyz lib2/abcdedd 
like image 528
Pekka Avatar asked Jul 18 '10 11:07

Pekka


1 Answers

Write a function longest_common_prefix that takes two strings as input. Then apply it to the strings in any order to reduce them to their common prefix. Since it is associative and commutative the order doesn't matter for the result.

This is the same as for other binary operations like for example addition or greatest common divisor.

like image 115
starblue Avatar answered Oct 04 '22 00:10

starblue