Last active
January 15, 2019 20:41
-
-
Save mizhi/374c1462f98feaf71b27f9d22710ebfb to your computer and use it in GitHub Desktop.
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
| /* *[Condencing Sentences]* | |
| Compression makes use of the fact that repeated structures are redundant, and | |
| it's more efficient to represent the pattern and the count or a reference to | |
| it. Siimilarly, we can condense a sentence by using the redundancy of | |
| overlapping letters from the end of one word and the start of the next. In this | |
| manner we can reduce the size of the sentence, even if we start to lose meaning. | |
| For instance, the phrase "live verses" can be condensed to "liverses". | |
| Writing a functiont that condenses an input string. | |
| ```Input: I heard the pastor sing live verses easily. | |
| Output: I heard the pastor sing liverses easily. | |
| Input: Deep episodes of Deep Space Nine came on the television only after the news. | |
| Output: Deepisodes of Deep Space Nine came on the televisionly after the news. | |
| Input: Digital alarm clocks scare area children. | |
| Output: Digitalarm clockscarea children.``` | |
| */ | |
| package main | |
| import ( | |
| "fmt" | |
| "os" | |
| "strings" | |
| ) | |
| func main() { | |
| original := os.Args[1:] | |
| fmt.Printf("Input : %s\n", strings.Join(original, " ")) | |
| fmt.Printf("Output: %s\n", strings.Join(condense(original, 0), " ")) | |
| } | |
| func condense(words []string, w1idx int) []string { | |
| w2idx := w1idx + 1 | |
| if w2idx >= len(words) { | |
| return words | |
| } | |
| word1, word2 := words[w1idx], words[w2idx] | |
| if commonText := suprefix(word1, word2); commonText != "" { | |
| word3 := word1 + strings.Replace(word2, commonText, "", 1) | |
| newWords := append(append(words[:w1idx], word3), words[w2idx+1:]...) | |
| return condense(newWords, w1idx) | |
| } | |
| return condense(words, w2idx) | |
| } | |
| func suprefix(s1, s2 string) string { | |
| var ret string | |
| for idx2 := range s2 { | |
| if strings.HasSuffix(s1, s2[0:idx2+1]) { | |
| ret = s2[0 : idx2+1] | |
| } | |
| } | |
| return ret | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment