www.jammni.de

Logo - Kleiner Drache
Login
Username:

Passwort:

Daten merken
Auto-Login
Registrieren
 
Online
niemand
 
Forumsuche
Suche nach:

Logo - DracheHaskell-Forum

Landei

Gepostet:
03.03.2011 20:55

Türme von Hanoi - iterativ  
Die Zugfolge für die Türme von Hanoi mit einer rekursiven Funktion zu ermitteln, ist ein Kinderspiel:

hanoi n = solve n 1 2 3

solve 0 _ _ _ = []
solve n from help to = (solve (n-1) from to help) ++ [(from,to)] ++ (solve (n-1) help from to)


Der iterative Algorithmus (siehe http://de.wikipedia.org/wiki/T%C3%BCrme_von_Hanoi#Iterativer_Algorithmus ) ist an sich schon schwieriger, aber meine Lösung kommt mir trotzdem ziemlich plump vor. Hat vielleicht jemand Verbesserungsvorschläge?


hanoi n = map rep $ solve [1..n] [] [] where
rep (x,y) | odd n = ([1,3,2] !! (x-1), [1,3,2] !! (y-1))
| otherwise = (x,y)

solve from help to = head $ mapMaybe ready $ iterate step (from,help,to,[]) where
step (1:xs,ys,zs,sol) = let (xs',zs',sol') = try xs zs 1 3 ((1,2):sol)
in (xs',1:ys,zs',sol')
step (xs,1:ys,zs,sol) = let (xs',ys',sol') = try xs ys 1 2 ((2,3):sol)
in (xs',ys',1:zs,sol')
step (xs,ys,1:zs,sol) = let (ys',zs',sol') = try ys zs 2 3 ((3,1):sol)
in (1:xs,ys',zs',sol')
try [] [] _ _ sol = ([],[], sol)
try (x:xs) [] a b sol = (xs,[x], (a,b):sol)
try [] (y:ys) a b sol = ([y],ys, (b,a):sol)
try (x:xs) (y:ys) a b sol | x < y = (xs,x:y:ys, (a,b):sol)
| y < x = (y:x:xs,ys, (b,a):sol)
ready ([],[],_,sol) = Just $ reverse sol
ready ([],_,[],sol) = Just $ reverse sol
ready _ = Nothing
Zum Seitenanfang    
 
Razor

Gepostet:
09.10.2011 11:30

   
Also, ich mache haskell nicht sehr lange und wies nicht inwieweit es sich bei dir anwenden lässt, doch du könnest es so machen wie ich in die sen modul:

-- Kompliziert

firstName :: Person -> String
firstName (Person firstname _ _ _ _ _) = firstname

lastName :: Person -> String
lastName (Person _ lastname _ _ _ _) = lastname

age :: Person -> Int
age (Person _ _ age _ _ _) = age

height :: Person -> Float
height (Person _ _ _ height _ _) = height

phoneNumber :: Person -> String
phoneNumber (Person _ _ _ _ number _) = number

flavor :: Person -> String
flavor (Person _ _ _ _ _ flavor) = flavor


-- einfach:

data Person = Person { firstName :: String
, lastName :: String
, age :: Int
, height :: Float
, phoneNumber :: String
, flavor :: String
} deriving (Show)




Wie gesagt ich machs nicht sehr lange , aber ich hoffe ich konnte dir doch irenwie helfen
Zum Seitenanfang    
 
Landei

Gepostet:
10.10.2011 10:01

   
Wenn dann bräuchte ich eine Art \"zyklische\" Datenstruktur. Auf die einzelnen Teile kann ich schon bequem zugreifen, ich brauchte etwas, das auch irgendwie Rotationen berücksichtigt. Aber der Denkanstoß in Richtung Datenstruktur ist schonmal gut.
Zum Seitenanfang