HiveBrain v1.2.0
Get Started
← Back to all entries
patterncModerate

The veiled guise of binary and string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theveiledbinaryguiseandstring

Problem

Challenge

Conceal a binary code within a word.

Specifications

  • The first argument is a path to a file.



  • The file contains multiple lines.



  • Each line is a test case represented by a space separated word and a binary code.



  • For each test case, print the binary masked word.



  • The mask alters the word according to the following:



  • If the bit is 1, change the letter to upper case.



  • If the bit is 0, leave the letter as is.



Constraints

  • Words are from 1 to 20 letters long.



  • The length of each word is equal to the length of the binary code.



  • Words are always in lower case.



  • The number of test cases is 40.



Sample Input


hello 11001

world 10000

cba 111

Sample Output


HEllO

World

CBA

Source

My Solution

#include 
#include 

#define LINE_BUFFER 42

int main(int argc, char *args[]) {
    if (argc  2) {
        puts("Excessive arguments, only the first will be considered.");
    }

    FILE *file = fopen(args[1], "r");
    if (file == NULL) {
        puts("Could not access file / file not found.");
        return 1;
    }

    char line[LINE_BUFFER];
    while (fgets(line, LINE_BUFFER, file)) {
        for (int i = 0, word_length = 0; ; i++, word_length++) {
            if (line[i] == ' ') {
                line[i++] = '\0';
                for (int j = 0; j < word_length; j++, i++) {
                    if (line[i] == '1') {
                        line[j] = toupper(line[j]);
                    }
                }
                printf("%s\n", line);
                break;
            }
        }
    }

    fclose(file);
}

Solution

-
42

#define LINE_BUFFER 42


42 is not a buffer. Besides being a meaning of life, the universe, and everything, it is size. Consider renaming it to LINE_BUFFER_LENGTH.

-
No naked loops

Every loop represents some algorithm, and therefore deservers a name. Consider

while (fgets(line, LINE_BUFFER, file)) {
    char * mask = find_separator(line);
    *mask++ = '\0';
    convert_word_according_to_mask(line, mask);
    printf("%s\n", line);
}


-
Errors (like fopen returning NULL) are better handled with perror() or strerror(errno). Both functions precisely describe what went wrong.

Code Snippets

#define LINE_BUFFER 42
while (fgets(line, LINE_BUFFER, file)) {
    char * mask = find_separator(line);
    *mask++ = '\0';
    convert_word_according_to_mask(line, mask);
    printf("%s\n", line);
}

Context

StackExchange Code Review Q#140595, answer score: 11

Revisions (0)

No revisions yet.