user3495272
user3495272

Reputation: 11

ordering in modified/deranged alphabet in haskell

I have a string containing the whole alphabet and then I want a different string from it by choosing a keyword and adding it to an exact position and then ordering the rest of the characters of the alphabet.

For example with a keyword gamer and a starting position given by 'l' the result should be -> "abcdefghijklmnopqrstuvwxyz" "opqstuvwxyzgamerbcdfhijkln"

I have seen this is used in the modified caesar cipher but I haven't found a solution for this part of the algorithm.

================================================================================= Now what I have been able to write is the following :

import List
derange key char = (fst(divided char)\\key) ++ key ++ (snd(divided char)\\key)
abc = ['a'..'z']
divided char = break (char==) abc

and the given output for an example is ->

Main> derange "ploting" 'g'

"abcdefplotinghjkmqrsuvwxyz"

So from the position of 'g' I wrote the keyword "ploting" and the rest of the alphabet is added without duplicate characters.

But still there is a little problem because the rest of the alphabet should continue from the first possible character after the keyword. So instead the right output should be "uvwxyzplotingabcdefhjkmqrs".

Change

So I worked on the code, to obtain the result I wanted. At first I tried it with concrete given values for the keyword and the character. What I have come to is the following :

`concat[drop (length['a'..'z'] - index('a','z') 'l') "gamerbcdfhijklnopqstuvwxyz",take    (length['a'..'z'] - index('a','z') 'l') "gamerbcdfhijklnopqstuvwxyz"]`

And the result is

"opqstuvwxyzgamerbcdfhijkln" 

,just what I wanted.

But then I tried to generalize the code so I wrote this.

import List
derange key char = concat [drop (length abc - index('a','z') char) def, 
take (length abc - index('a','z') char) def]
where abc = ['a'..'z']
def = key ++ (key\\abc)

But now the output is

Main> derange "gamer" 'l'
"gamer" 

and I don't know why. Any suggestions?

Found the problem, just had to swap key and abc within the list difference. Now I get the desired output.

Upvotes: 0

Views: 474

Answers (1)

cdk
cdk

Reputation: 6778

Your question is a little unclear on what the expected behaviour of derange is supposed to be. This seems to match your description

import Data.List ((\\))

-- returns the 0-based index of c in ['a' .. 'z']
index :: Char -> Int
index c = fromEnum c - 97

derange :: Char -> String -> String
derange key str =
    drop (i - length str) (tail bs ++ str ++ as)
    where (as, bs) = splitAt i $ ['a' .. 'z'] \\ str
          i = index key

sample output,

λ. derange 'g' "ploting"
"jkmqrsuvwxyzplotingabcdef"

Upvotes: 1

Related Questions