You are given string
$S containing alphabets A..Z only and a number
Write a script to encrypt the given string
$S using Caesar Cipher with left shift of size
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.
substrto create the cipher table
- Create a
%mappinghash mapping plain text characters to their cipher equivalent.
- Use split, map and join to generate the cipher text, and then display it
» ./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
You are given a binary string
$B and an integer
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.
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
unpackto break up the binary value into the array
- 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
- Finally, I go through each
@chunkand each character, and add to the
$flipsvalue if the bit is different from that in the
$most_usedstring. 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.
» ./ch-2.pl 101100101 3 1 » ./ch-2.pl 10110111 4 2