Created
October 28, 2016 05:08
-
-
Save RameshRM/f722bb0c533423093e3698b7991aa25d to your computer and use it in GitHub Desktop.
This file contains 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
'use strict'; | |
var input = 'this is a test string'; | |
input = 'aaaabbbcccdddcdbaaa'; | |
var match = 'tist'; //accb | |
match = 'abc'; | |
input = 'abcdefadfafaefd'; | |
match = 'ef'; | |
var matches = []; | |
var charbuilder = buildCharCount(match); | |
for (var i = 0; i < input.length; i++) { | |
if (hasMatch(input.substr(i), match)) { | |
matches.push(input.substr(i)); | |
} | |
} | |
var minSubstr; | |
var minSubstrIdx = 0; | |
var pre; | |
var hasMatch; | |
for (var i = 0; i < matches.length; i++) { | |
hasMatch = false; | |
var matchCharBuilder = buildCharCount(matches[i]); | |
if (minSubstr === undefined) { | |
hasMatch = true; | |
minSubstr = matches[i].length; | |
minSubstrIdx = 0; | |
} else { | |
Object.keys(charbuilder.charMap).forEach(function forEach(key) { | |
if (matchCharBuilder.charMap[key] && matchCharBuilder.charMap[key] >= charbuilder.charMap[key]) { | |
hasMatch = true; | |
} | |
}); | |
if (hasMatch) { | |
pre = minSubstr; | |
minSubstr = Math.min(minSubstr, matches[i].length); | |
if (minSubstr !== pre) { | |
minSubstrIdx = i; | |
} | |
} | |
} | |
} | |
console.log('minSubstrIdx', minSubstrIdx, matches[minSubstrIdx]); | |
function hasMatch(input, target) { | |
for (var i = 0; i < target.length; i++) { | |
if (input.indexOf(target[i]) < 0) { | |
return false; | |
} | |
} | |
return true; | |
} | |
function buildCharCount(input) { | |
var charCount = []; | |
var charMap = {}; | |
for (var i = 0; i < input.length; i++) { | |
if (charMap[input[i]]) { | |
charMap[input[i]]++; | |
} else { | |
charMap[input[i]] = 1; | |
} | |
} | |
var charCount = Object.keys(charMap).map(function map(item) { | |
return charMap[item]; | |
}); | |
return { | |
charMap: charMap, | |
charCount: charCount, | |
sum: function(input) { | |
return charCount.reduce(function(previousValue, currentValue, currentIndex, array) { | |
return previousValue + currentValue; | |
}); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment