# TASK #1 › Caesar Cipher

## The task

You are given string `$S`

containing alphabets A..Z only and a number `$N`

.

Write a script to encrypt the given string `$S`

using Caesar Cipher with left shift of size `$N`

.

## My solution

First thing to note is the tr function does not support string interpolation, as the translation table is built at compile time.

I broke down the task into these steps:

- Check the string only contains A - Z and spaces. Check the number is an integer between 1 and 25.
- Use
`substr`

to create the cipher table - Create a
`%mapping`

hash mapping plain text characters to their cipher equivalent. - Use split, map and join to generate the cipher text, and then display it

## Examples

```
» ./ch-1.pl "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG" 3
QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD
» ./ch-1.pl "QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD" 23
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
```

# TASK #2 › Binary Substrings

## The task

You are given a binary string `$B`

and an integer `$S`

.

Write a script to split the binary string `$B`

of size `$S`

and then find the minimum number of flips required to make it all the same.

## The solution

This is one of those tasks where the solution I submit isn't the fastest one, but one that is well explained.

- I first check that the binary value contains only 0's and 1's. I also check the second value is a positive integer. While the tasks that $S is an integer, a zero or negative integer is nonsensical in this sense.
- I add leading zeros to the binary value if it's length is not dividable by the integer. I think use
`unpack`

to break up the binary value into the array`@chunks`

- Next I work through each character position determining whether the bit is set (1) or not set (0) more frequently. If it's half and half, I use '0' but could use '1' as it would give the same result. The resulting value is stored as
`$most_used`

- Finally, I go through each
`@chunk`

and each character, and add to the`$flips`

value if the bit is different from that in the`$most_used`

string. I then display the minimum number of flips required.

This code could more concise by skipping the last step and doing the calculations in the third step. For example, if the first character was '0, 1, 1, 1' then we would only need one flip to make them all the same.

## Examples

```
» ./ch-2.pl 101100101 3
1
» ./ch-2.pl 10110111 4
2
```

## Top comments (0)