import Data.List

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

type Faces = [Int]
type Roll  = String
type Dice  = [Roll]
formatIn :: String -> (Dice, [Faces])
formatIn = (\(x:_:ys) -> (words x,map (map read.words)  ys)).lines
 
solve :: (Dice, [Faces]) -> [Roll]
solve (x,ys) = map (label x) ys
 
label :: Dice -> Faces -> Roll
label dice rolls = (!!) dice $f rolls 
    where f rolls 
            | isInfixOf rolls [2,3,5,4,2] = 0
            | isInfixOf rolls [1,4,6,3,1] = 1
            | isInfixOf rolls [1,2,6,5,1] = 2
            | isInfixOf rolls [1,5,6,2,1] = 3
            | isInfixOf rolls [1,3,6,4,1] = 4
            | isInfixOf rolls [2,4,5,3,2] = 5