Ruby, 211 207 203 196 characters
Thanks to edc65 for 4 characters
->(x){x=x.chars
o,b,c=x.size
l=o*2+1
a=Array.new(l){Array.new l,' '}
a[o][o]=x.delete_at o/2
a[b][c]=x.pop if a[b=rand(l)][c=rand(l)]==' '&&(b-o)**2+(c-o)**2<=o*o while x[0]
a.map(&:join).join $/}
Explanation:
->(x){...}
define an anonymous function that takes in an argument x
x=x.chars
transform x
from a string into an array of one-character strings
o,b,c=x.size
store the length of the input in o
for later use. b
and c
simply need to be initialized to something, so save 2 characters by attaching to a previous assignment.
l=o*2+1
this is the length/width of the field where all characters could possibly go, also the diameter of the explosion circle.
Array.new(l){Array.new l,' '}
make an l
xl
sized 2D array of space characters.
a[o][o]=x.delete_at o/2
sets the center of the array to the center of the values of x
(the input), while deleting that value from x
... while x[0]
run the block (in this case, the code before while
because it is inline) over and over until x
is empty. In ruby, accessing an index that does not exist returns nil
, which is a falsey value.
a[b=rand(l)][c=rand(l)]==' '
Assign b
and c
to random values where 0 <= n < l
. Then check if the spot at b
,c
is empty (aka is set to space character)
(b-o)**2+(c-o)**2<=o*o
Pythagorean distance check. o
is the length of the input. **
is ruby's exponentiation operator, and val<=o*o
is shorter than val**0.5<=o
.
a[b][c]=x.pop
delete the last value from x
. Set the position a
,b
to that value in array a
a[b][c]=x.pop if a[b=rand(l)][c=rand(l)]==' '&&(b-o)**2+(c-o)**2<=o*o while x[0]
Set a random position to the last value if that position is free and is within the explosion radius; keep doing this until we run out of characters to place.
$/
is set to the operating system's newline. It's also shorter than "\n"
a.map(&:join).join $/
Map all the arrays in a
to a single-string version of themselves (eg ['a','b','c']
-> 'abc'
). Take that new array and join it with newlines. Implicit return.
Selecting position randomly, one char could go in the same position of an other and overwrite it. Is this alllowed? (My suggestion: no) – edc65 – 2016-01-24T09:38:50.593
You are right: No. – Mama Fun Roll – 2016-01-24T16:52:07.050
1What on earth does this have to do with blowing me up? (I genuinely don't understand the relevance of the title...) – cat – 2016-01-25T00:08:12.493
1@cat This is a modification of a cat program, except that you explode the input. – Mama Fun Roll – 2016-01-25T00:55:00.063
3A little bit related – Mego – 2016-01-25T19:31:12.037