14
1
Motivation
In this challenge your task was to multiply two strings, this naturally introduces a way to take the square root of a string.
How does it work?
Given a string (for example pub
) the first thing you need to do, is to determine the ASCII code for each character:
"pub" -> [112, 117, 98]
Next you map these codes to the range [0..94]
by subtracting 32
of each value:
[112, 117, 98] -> [80, 85, 66]
Now you need to find for each value its root modulo 95
(eg. 40*40 % 95 = 80
, you could also pick 55
):
[80, 85, 66] -> [40, 35, 16]
And finally you'll map it back to the range [32..126]
and convert it back to a string:
[40, 35, 16] -> [72, 67, 48] -> "HC0"
Indeed "HC0" ⊗ "HC0" = "pub"
as you can verify with a solution from the other challenge here.
The ones familiar with modular arithmetic probably noticed that the square root modulo 95
does not always exist, for example there's no root for 2
. In such a case the square root of a string is not defined and your program/function may crash, loop indefinetly etc.
For your convenience, here's the list of chars that have a square root (the first one is a space):
!$%&)+03489:>CDGLMQVW]`bjlpqu
Rules
- You will write a program/function that takes a string (or list of chars) as an argument and returns any square root if it exists
- You may assume that the input always has a square root
- The input may consist of an empty string
- The input will be in the printable range (
[32..126]
) - The output is either printed to the console or you return a string if the square root exists
- In case the square root doesn't exist, the behavior of your program/function is left undefined
- If you choose to print the root to the console trailing newlines or whitespaces are fine
Test cases
Note that these are not necessarily the only solutions:
'' -> ''
'pub' -> 'HC0'
'pull!' -> 'HC33!'
'M>>M' -> '>MM>'
'49' -> '4%'
'64' -> undefined
'Hello, World!' -> undefined
Forcing an error state on these characters without a square root seems unnecessary, I'd recommend just undefined behavior. – ATaco – 2017-07-26T04:21:03.503
@ATaco I updated the challenge. – ბიმო – 2017-07-26T04:40:25.630
What to do if the given string is the square of multiple strings? – tsh – 2017-07-26T06:26:10.287
@tsh Return any, I'll update the challenge. – ბიმო – 2017-07-26T07:02:17.330
@Downvoter Why the downvote? – ბიმო – 2017-07-26T10:26:02.127
Is it deliberate that you map to the range 0-95 and then take modulo 95 instead of 96? – curiousdannii – 2017-07-26T12:34:25.523
1@curiousdannii Actually it should be the range
0-94
(that's the printable range), that's a typo - sorry about that. – ბიმო – 2017-07-26T12:39:33.533Can the output be a list of chars? – Oliver – 2017-07-26T17:57:39.703
@Oliver Yes, it can. – ბიმო – 2017-07-26T18:34:31.600