Created
November 13, 2016 10:13
-
-
Save johncarney/ef355be7eac16b96ca0f09bafad5e389 to your computer and use it in GitHub Desktop.
Find the longest common prefix of a bunch of arrays, or a bunch of strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def common_array_prefix(*arrays) | |
| arrays.reduce do |a, b| | |
| index = a.zip(b).index { |x, y| x != y } | |
| a[0...index] | |
| end | |
| end | |
| def common_string_prefix(*strings) | |
| common_array_prefix(*strings.map(&:chars)).join("") | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment