Set 1, Challenge 3

This commit is contained in:
Miroslav Vasilev 2024-10-28 22:15:03 +02:00
parent 4b789cf646
commit 17aa6a2fcc
2 changed files with 69 additions and 0 deletions

46
set1/challenge_3.go Normal file
View file

@ -0,0 +1,46 @@
package set1
const SomeShakespeare = "That can I, At least, the whisper goes so: our last king, Whose image even but now appeared to us, Was, as you know, by Fortinbras of Norway, Thereto pricked on by a most emulate pride, Dared to the combat, in which our valiant Hamlet - For so this side of our known world esteemed him - Did slay this Fortinbras, who by a sealed compact, Well ratified by law and heraldry, Did forfeit, with his life, all those his lands Which he stood seized on to the conqueror: Against the which, a moiety competent Was gaged by our king, which had returned To the inheritance of Fortinbras, Had he been vanquisher, as, by the same cov'nant, And carriage of the article designed, His fell to Hamlet. Now, sir, young Fortinbras, Of unimprovèd mettle hot and full, Hath in the skirts of Norway here and there Sharked up a list of landless resolutes For food and diet to some enterprise That hath a stomach in't, which is no other - And it doth well appear unto our state - But to recover of us, by strong hand And terms compulsative, those foresaid lands So by his father lost: and this, I take it, Is the main motive of our preparations, The source of this our watch and the chief head Of this post-haste and rummage in the land."
func FindMostCommonByteInText(text string) byte {
encounteredBytes := map[byte]int{}
var mostCommonByteCount int
var mostCommonByte byte
for i := 0; i < len(text); i++ {
if text[i] == ' ' {
continue
}
count, exists := encounteredBytes[text[i]]
if !exists {
encounteredBytes[text[i]] = 1
} else {
encounteredBytes[text[i]] = count + 1
}
if (count + 1) > mostCommonByteCount {
mostCommonByteCount = count + 1
mostCommonByte = text[i]
}
}
return mostCommonByte
}
func XORDecode(hexString string, passChar byte) string {
decoded, success := HexDecode(hexString)
if !success {
return ""
}
buffer := make([]byte, len(decoded), len(decoded))
for i := 0; i < len(decoded); i++ {
buffer[i] = decoded[i] ^ passChar
}
return string(buffer)
}

View file

@ -30,3 +30,26 @@ func Test_Challenge2(t *testing.T) {
t.Fatal(("Set 1, Challenge 2 has failed"))
}
}
func Test_Challenge3(t *testing.T) {
const encodedString = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
var passChar, mostCommonByte byte
var text string
for i := 0; i < len(letters); i++ {
letter := letters[i]
result := set1.XORDecode(encodedString, letter)
mostCommonLetter := set1.FindMostCommonByteInText(result)
if mostCommonLetter > mostCommonByte {
mostCommonByte = mostCommonLetter
text = result
passChar = letter
}
}
t.Logf("Result:\n\tEncoding char: %c\n\tMost common letter: %c\n\tText: %v", passChar, mostCommonByte, text)
}