Created
December 18, 2015 17:44
-
-
Save faethonm/c56d0748c87d68ea036e to your computer and use it in GitHub Desktop.
If X and Y are two strings of equal length N, then the difference between them is defined as the number of indices i where the i-th character of X and the i-th character of Y are different.
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 distance(a,b) | |
a.split('').zip(b.split('')).select{|a,b| a!=b}.count | |
end | |
def min_differences(a,b) | |
distances = (0..(b.length - a.length)).map do |index| | |
b_sub = b[index...a.length+index] | |
distance(a,b_sub) | |
end | |
distances.min | |
end | |
min_differences('chunky', 'nofunky') #=> 2 | |
min_differences('hello', 'xello') #=> 1 | |
min_differences('adaabc', 'aababbc') #=> 2 | |
min_differences('giorgi', 'igroig') #=> 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For example, the difference between the words "ant" and "art" is 1. You are given two Strings, A and B, where the length of A is less than or equal to the length of B. You can apply an arbitrary number of operations to A, where each operation is one of the following: Choose a character c and add it to the beginning of A. Choose a character c and add it to the end of A. Apply the operations in such a way that A and B have the same length and the difference between them is as small as possible. Return this minimum possible difference. Example 1 input: "chunky", "nofunky" output: 2 You can prepend "n" to "chunky" and you'll get "nchunky". The difference between "nchunky" and "nofunky" is 2. Example 2 input: "hello", "xello" output: 1 Example 3 input: "adaabc", "aababbc" output: 2 Example 4 input: "giorgi", "igroig" output: 6