Pelin
Pelin

Reputation: 127

Conditions in a list comprehension , finding possibilities

there are 3 keys and 3 locks, and i have to write a code to show the possible tries. Rules are:


I want to change this code in a way that, instead of " fst <- [3] " it says; " fst cannot be [1] " and I also want to add that 2 cannot come before 1. I tried it with (elemIndex 2 (x,y,z)) > (elemIndex 1 (x,y,z)) but it didn't work. I would appreciate for some ideas.

d = [(x,y,z) | x <- [1..3], y <- [1..3], z <-[1..3], fst <- [3] , tail <- 1], x /= y, y /= z, x /= z]

Upvotes: 1

Views: 82

Answers (1)

Ami Tavory
Ami Tavory

Reputation: 76297

You could use something like this:

d = [(3, y, z) | y <- [1..2], z <-[1..2], y /= z, y /= 2]

which gives

[(3,1,2)]

Explanation

First key cannot be placed as the first one.

and

Second key never can be placed before the first one.

imply that x cannot be 1 or 2, and hence must be 3. This gives

[(3, y, z) | y <- [1..2], z <-[1..2]

Since

No keys can be tried more than once.

we also have

, y != z

Finally

Second key never can be placed before the first one.

gives

, y /= 2]

In fact, with some thought, you could argue that you can just write

d = [(3, 1, 2)]

Upvotes: 1

Related Questions