DEV Community

Simon Green
Simon Green

Posted on

The odd binary string

Weekly Challenge 193

Challenge, My solutions

Two relatively straight forward tasks this week, so not as much commentary as usual.

Task 1: Binary String

Task

You are given an integer, $n > 0.

Write a script to find all possible binary numbers of size $n.

My solution

Thankfully both Python and Perl provide easy methods to convert a (base 10) integer into a binary number with leading zeros. For the integer x with y leading zeros, we can use format(x, '0yb') in Python, and sprintf('%0yb', x) in Perl.

With that out of the way, we know that all binary numbers can be converted from the integers between 0 and 2n-1 (inclusive).

Examples

$ ./ch-1.py 2
00, 01, 10, 11

$ ./ch-1.py 3
000, 001, 010, 011, 100, 101, 110, 111
Enter fullscreen mode Exit fullscreen mode

Task 2: Odd String

Task

You are given a list of strings of same length, @s.

Write a script to find the odd string in the given list. Use positional value of alphabet starting with 0, i.e. a = 0, b = 1, ... z = 25.

Find the difference array for each string as shown in the example. Then pick the odd one out.

My solution

This task can be broken into three sub tasks:

  1. Create a dict (hash in Perl) called letter_map that maps the letters of the alphabet to integers, where letter_map['a'] is 0, and letter_map['z'] is 25.
  2. Convert each word into a space separated values of differences. So adc is converted to 3 -1. With this information I have an occurrences dict where the key is the converted string and the value is a list of words that match that pattern.
  3. Calculate an array unique_words of values in occurrences that only have one value. If there is only one unique word, I display that. If not, I display an error.

Examples

$ ./ch-2.py adc wzy abc
abc

$ ./ch-2.py aaa bob ccc ddd
bob
Enter fullscreen mode Exit fullscreen mode

Top comments (0)