import Data.List

main :: IO()
main = getContents >>= putStr.unlines.map show.solve.formatIn

type Faces = [Int]
type Roll  = Int
type Dice  = [Roll]
formatIn :: String -> (Dice, [Faces])
formatIn = (\(x:_:ys)->(x,ys)).map (map (read :: String->Int).words).lines

solve :: (Dice, [Faces]) -> [Roll]
solve (x,ys) = map (label x) ys
 
label :: Dice -> Faces -> Roll
label dice@[x1,x2,x3,x4,x5,x6] rolls = (!!) dice $f rolls 
    where f rolls 
            | isInfixOf rolls [x2,x3,x5,x4,x2] = 0
            | isInfixOf rolls [x1,x4,x6,x3,x1] = 1
            | isInfixOf rolls [x1,x2,x6,x5,x1] = 2
            | isInfixOf rolls [x1,x5,x6,x2,x1] = 3
            | isInfixOf rolls [x1,x3,x6,x4,x1] = 4
            | isInfixOf rolls [x2,x4,x5,x3,x2] = 5