Morse Code – Words
Decode a message from Morse code represented by consecutive 1's where each group corresponds to a letter of the alphabet
Understand the Problem
Problem Statement
Morse Code – Words: A spaceship has exploded in space and two survivors need to communicate with the station on Earth. Due to voice communication failure, they can only hear beep sounds. Each consecutive beep sound denotes an alphabet letter. For example, two consecutive beep sounds means the letter 'b'. The beep sounds are represented as 1's. Groups of consecutive 1's are given as input in each line. Help the crew decode the message.
Note: Read the input carefully to avoid errors.
Constraints
- 1 ≤ Number of lines ≤ 100
- 1 ≤ Number of 1's in a line ≤ 1000
- Each group of 1's represents a single lowercase letter (a-z)
- The number of consecutive 1's maps to the letter position in alphabet (1=a, 2=b, ..., 26=z)
Examples
111 1 11111111111111
1111111111111111111111111 111111111111111 111111111111111111111
11111111 11111 1 111111111111111111
1111111111111 11111can you hear meThe first line '111 1 11111111111111' decodes to 'can' (111=3=c, 1=1=a, 11111111111111=14=n). The second line decodes to 'you', the third to 'hear', and the fourth to 'me'. Spaces between groups form words.
11 1111111 1111
1111111 111111111111 1
11111 11111111 11 1111111 11111111 111
11 11111111 1111 11111111
1 11 11 1bgd gla ehbghc bhdh abbaEach group of 1's converts to a letter: 11=2=b, 1111111=7=g, 1111=4=d, etc. The input forms the message 'bgd gla ehbghc bhdh abba'.
Solution
#include <stdio.h>
#include <string.h>
int main() {
char line[10000];
int firstWord = 1;
while (fgets(line, sizeof(line), stdin) != NULL) {
int len = strlen(line);
int count = 0;
int firstChar = 1;
if (!firstWord) {
printf(" ");
}
firstWord = 0;
for (int i = 0; i < len; i++) {
if (line[i] == '1') {
count++;
} else if (line[i] == ' ' || line[i] == '\n' || line[i] == '\0') {
if (count > 0) {
if (!firstChar) {
printf(" ");
}
printf("%c", count + 96);
count = 0;
firstChar = 0;
}
}
}
}
return 0;
}The C solution reads input line by line using fgets(). For each line, it iterates character by character, counting consecutive '1' characters. When it encounters a space, newline, or end of string, it converts the count to the corresponding letter using count + 96 (since ASCII 'a' is 97). Letters are printed with spaces between them, and words are separated by spaces between lines.
Key points:
- Uses
fgets()for safe line reading - Tracks word boundaries with
firstWordflag - Converts count to letter using ASCII arithmetic
- Handles multiple spaces between groups correctly