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)

/**
  * http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_11_B&lang=jp
  * Structure and Class - Dice II
  */
object Main {

  class Dice(numbers: IndexedSeq[Int]) {
    def apply(number: Int): Int = {
      numbers(number)
    }

    def rotateTo(direction: Char): Dice = {
      direction match {
        case 'N' => new Dice(IndexedSeq(numbers(1), numbers(5), numbers(2), numbers(3), numbers(0), numbers(4)))
        case 'S' => new Dice(IndexedSeq(numbers(4), numbers(0), numbers(2), numbers(3), numbers(5), numbers(1)))
        case 'W' => new Dice(IndexedSeq(numbers(2), numbers(1), numbers(5), numbers(0), numbers(4), numbers(3)))
        case 'E' => new Dice(IndexedSeq(numbers(3), numbers(1), numbers(0), numbers(5), numbers(4), numbers(2)))
      }
    }

    def find(number: Int): Int = {
      numbers.indexWhere(_ == number)
    }
  }

  def main(args: Array[String]): Unit = {
    val dice = new Dice(io.StdIn.readLine().split(" ").map(_.toInt))
    val questions = io.StdIn.readInt()
    Iterator.continually(io.StdIn.readLine()).takeWhile(_ != null).map(_.split(" ").map(_.toInt))
      .take(questions)
      .map {
        case Array(top, front) => determineRight(dice, top, front)
      }
      .foreach(println)
  }

  def determineRight(dice: Dice, top: Int, front: Int): Int = {
    val operationsToTop = Seq("", "N", "W", "E", "S", "NN")
    val operationsToFront = Seq("S", "", "WSE", "ESW", "SEEN", "N")
    val dice2 = operationsToTop(dice.find(top)).foldLeft(dice)(_.rotateTo(_))
    val dice3 = operationsToFront(dice2.find(front)).foldLeft(dice2)(_.rotateTo(_))
    dice3(2)
  }
}