Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Dice II

Construct a dice from a given sequence of integers in the same way as Dice I.

You are given integers on the top face and the front face after the dice was rolled in the same way as Dice I. Write a program to print an integer on the right side face.

Input

In the first line, six integers assigned to faces are given in ascending order of their corresponding labels.
In the second line, the number of questions $q$ is given.

In the following $q$ lines, $q$ questions are given. Each question consists of two integers on the top face and the front face respectively.

Output

For each question, print the integer on the right side face.

Constraints

$0 \leq $ the integer assigned to a face $ \leq 100$

The integers are all different

$1 \leq q \leq 24$

Sample Input

1 2 3 4 5 6
3
6 5
1 3
3 2

Sample Output

3
5
6

Solution in Scala (judge verdict: Accepted)

import scala.io.StdIn._
import scala.annotation.tailrec

object Main {

  final case class Rotation(run: Dice => Dice){
    final def apply(d: Dice): Dice = run(d)
    final def compose(other: Rotation): Rotation = Rotation(run compose other.run)
    final def andThen(other: Rotation): Rotation = other compose this
  }

  object Rotation {
    final def id = Rotation(d => d)
    final def north = Rotation(d => Dice(List(1,5,2,3,0,4).map(d.pip)))
    final def east = Rotation(d => Dice(List(3,1,0,5,4,2).map(d.pip)))
    final def ccw = Rotation(d => Dice(List(0,3,1,4,2,5).map(d.pip)))

    final def axial(rotation: Rotation): Seq[Rotation] =
      for(i <- 0 to 3) yield List.fill(i)(rotation).fold(id)(_ compose _)

    def enumerateTop(): Seq[Rotation] =
      for(i <- 1 to 6) yield ((0 to i).map(j => if(j % 2 == 0) north else east)).fold(id)(_ compose _)

    def enumerate: Seq[Rotation] = enumerateTop().flatMap(e => axial(ccw).map(e compose _))
  }

  case class Dice(pip: List[Int]){
    lazy val all: Seq[Dice] = Rotation.enumerate.map(_.run(Dice(pip)))
    def ===(that: Dice): Boolean = pip.corresponds(that.pip)(_ == _)
    def ==(that: Dice): Boolean = all.exists(_ === that)
  }

  @tailrec
  def loop(n:Int, all: Seq[Dice]):Unit = if(n>0){
    val Array(a,b,_*) = readLine.split(" ").map(_.toInt)
    val res = all.filter(d => d.pip(0)==a && d.pip(1)==b)
    println(res(0).pip(2))
    loop(n-1,all)
  }

  def main(args: Array[String]): Unit = {
    val pip = readLine.split(" ").map(_.toInt).toList
    val all: Seq[Dice] = Rotation.enumerate.map(_.run(Dice(pip)))
    val Array(n,_*) = readLine.split(" ").map(_.toInt)
    loop(n,all)
  }

}