Google
Information Storage and Retrieval: Multiply the strings! (SQL Puzzle 20)

Pages

Wednesday, August 27, 2008

Multiply the strings! (SQL Puzzle 20)

Problem:
The result of the multiplication of a given string by a given number is defined as follows:
1. A string multiplied by 0 is empty.
2. A string multiplied by a positive number x , is concatenation of string x number of times:
e.g Gaurav multiplied by 2 results GauravGaurav
3. A string multiplied by a negative number x , is concatenation of reverse og string x number of times:
e.g Gaurav multiplied by -2 results varuaGvaruaG

Write an SQL query to achieve this.

Solution:

select final_word
from
(
select
case when given_number>0 then replace(sys_connect_by_path(given_word,'\'),'\','') else reverse(replace(sys_connect_by_path(given_word,'\'),'\','')) end final_word,
given_word,
given_number
from
(
select
given_word,
given_number,
rownum rn
from
(
select 'gaurav' given_word, -2 given_number from all_objects
)
where
rownum<=abs(given_number)
)
connect by rn=rn
and rownum<=rn
)
where length(final_word)=length(given_word)*abs(given_number)

No comments: