# Permutación de elementos consecutivos

Definir la función

` permutaConsecutivos :: [a] -> [a]`

tal que (permutaConsecutivos xs) es la lista obtenida permutando los elementos consecutivos de xs. Por ejemplo,

``` permutaConsecutivos [1..8] == [2,1,4,3,6,5,8,7] permutaConsecutivos [1..9] == [2,1,4,3,6,5,8,7,9] permutaConsecutivos "simplemente" == "ispmelemtne"```

#### Soluciones

```import Data.Array   -- 1ª solución -- ===========   permutaConsecutivos :: [a] -> [a] permutaConsecutivos (x:y:zs) = y : x : permutaConsecutivos zs permutaConsecutivos xs = xs   -- 2ª solución -- ===========   permutaConsecutivos2 :: [a] -> [a] permutaConsecutivos2 xs | even n = elems (array (1,n) [(i,f i) | i <- [1..n]]) | otherwise = elems (array (1,n) ((n,v!n) : [(i,f i) | i <- [1..n-1]])) where n = length xs v = listArray (1,n) xs f i | even i = v ! (i - 1) | otherwise = v ! (i + 1)   -- Comparación de eficiencia -- =========================   -- La comparación es -- λ> length (permutaConsecutivos [1..(3*10^6)]) -- 3000000 -- (2.21 secs, 504,102,648 bytes) -- λ> length (permutaConsecutivos2 [1..(3*10^6)]) -- 3000000 -- (6.18 secs, 1,248,127,688 bytes)```

#### Pensamiento

Entre el vivir y el soñar
hay una tercera cosa.

Inicial

## 8 soluciones de “Permutación de elementos consecutivos”

1. frahidzam
```permutaConsecutivos :: [a] -> [a] permutaConsecutivos [] = [] permutaConsecutivos [x] = [x] permutaConsecutivos (x:y:xs) = y:x:(permutaConsecutivos xs)```
```permutaConsecutivos :: [a] -> [a] permutaConsecutivos = concatMap reverse. divide   divide :: [a] -> [[a]] divide [] = [] divide [x] = [[x]] divide (x:y:xs) = [x,y]:divide xs```
3. luipromor
```permutaConsecutivos :: [a] -> [a] permutaConsecutivos [] = [] permutaConsecutivos [x] = [x] permutaConsecutivos (x:y:xs) = y:x: permutaConsecutivos xs```
4. javmarcha1
```  permutaConsecutivos :: [a] -> [a] permutaConsecutivos xs | length xs < 2 = xs permutaConsecutivos (x:y:xs) = y:[x] ++ permutaConsecutivos xs```
5. ireprirod
```permutaConsecutivos :: [a] -> [a] permutaConsecutivos [] = [] permutaConsecutivos [x] = [x] permutaConsecutivos (x:y:xs) = y:x:permutaConsecutivos xs```
6. frahidzam

Solución en Maxima

`permutaConsecutivos (xs) := if emptyp (xs) then [] elseif emptyp (rest(xs,1)) then [first (xs)] else append ([second (xs), first (xs)],permutaConsecutivos(rest (xs,2)))\$`
7. alebarmor1

```consec [] = []
consec [x] = [(x,x)]
consec (x:y:xs) = [(x,y)] ++ (consec xs)
twist p = (snd p, fst p)
giroLista xs = map (twist) xs
parALista p = [fst p, snd p]
listaParLista xs = concat (map (parALista) xs)
permutaConsecutivos xs = take (length xs) (listaParLista (giroLista (consec xs)))
```

8. ireprirod

Definición en Maxima:
permutaConsecutivos (xs):= if (emptyp (xs) or length (xs)=1) then xs
else cons(second(xs),cons(first(xs), permutaConsecutivos(rest(xs,2))))\$

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.