diff --git a/src/page-22/2325. Decode the Message/decodeMessage.test.ts b/src/page-22/2325. Decode the Message/decodeMessage.test.ts new file mode 100644 index 0000000..7aebb82 --- /dev/null +++ b/src/page-22/2325. Decode the Message/decodeMessage.test.ts @@ -0,0 +1,19 @@ +import { decodeMessage } from './decodeMessage'; + +describe('2325. Decode the Message', () => { + test('decodeMessage', () => { + { + const key = 'the quick brown fox jumps over the lazy dog'; + const message = 'vkbs bs t suepuv'; + const expected = 'this is a secret'; + expect(decodeMessage(key, message)).toBe(expected); + } + + { + const key = 'eljuxhpwnyrdgtqkviszcfmabo'; + const message = 'zwx hnfx lqantp mnoeius ycgk vcnjrdb'; + const expected = 'the five boxing wizards jump quickly'; + expect(decodeMessage(key, message)).toBe(expected); + } + }); +}); diff --git a/src/page-22/2325. Decode the Message/decodeMessage.ts b/src/page-22/2325. Decode the Message/decodeMessage.ts new file mode 100644 index 0000000..d5fc0f7 --- /dev/null +++ b/src/page-22/2325. Decode the Message/decodeMessage.ts @@ -0,0 +1,44 @@ +type DecodeMessage = (key: string, message: string) => string; + +/** + * Accepted + */ +export const decodeMessage: DecodeMessage = (key, message) => { + // Create a Map to store the substitution table + const substitutionMap = new Map(); + + // Define the regular English alphabet + const alphabet = 'abcdefghijklmnopqrstuvwxyz'; + + // Variable to keep track of the current index in the alphabet + let substitutionIndex = 0; + + // Loop through each character in the key string + for (const char of key) { + // Check if the character is a lowercase English letter and is not already in the map + if (char >= 'a' && char <= 'z' && !substitutionMap.has(char)) { + // Add the character to the map with its corresponding letter in the alphabet + substitutionMap.set(char, alphabet[substitutionIndex]); + + // Move to the next letter in the alphabet + substitutionIndex += 1; + } + } + + // Variable to store the decoded message + let decodedMessage = ''; + + // Loop through each character in the message string + for (const char of message) { + // If the character is a space, add a space to the decoded message + if (char === ' ') { + decodedMessage += ' '; + } else { + // Otherwise, substitute the character using the map and add it to the decoded message + decodedMessage += substitutionMap.get(char) || char; + } + } + + // Return the decoded message + return decodedMessage; +};