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 Ruby (judge verdict: Wrong Answer)

#!/usr/bin/env ruby
# vim:set fileencoding=utf-8:

class Dice

  def initialize( given_ary )
    @ary = given_ary
  end

  def topface( val )
    4.times do
      self.roll( "E" )
      if self.top == val
        return
      end
    end
    2.times do
      self.roll( "N" )
      if self.top == val
        return
      end
    end
  end

  def frontface( val )
    3.times do
      tmp = @ary[1]
      @ary[1] = @ary[2]
      @ary[2] = @ary[4]
      @ary[4] = @ary[3]
      @ary[3] = tmp
      if @ary[1] == val
        return
      end
    end
  end

  def roll( direction )
    case direction.downcase
    when "e"
      tmp = @ary[0]
      @ary[0] = @ary[3]
      @ary[3] = @ary[5]
      @ary[5] = @ary[2]
      @ary[2] = tmp
    when "w"
      tmp = @ary[0]
      @ary[0] = @ary[2]
      @ary[2] = @ary[5]
      @ary[5] = @ary[3]
      @ary[3] = tmp
    when "s"
      tmp = @ary[0]
      @ary[0] = @ary[4]
      @ary[4] = @ary[5]
      @ary[5] = @ary[1]
      @ary[1] = tmp
    when "n"
      tmp = @ary[0]
      @ary[0] = @ary[1]
      @ary[1] = @ary[5]
      @ary[5] = @ary[4]
      @ary[4] = tmp
    end
  end

  def top
    @ary[ 0 ]
  end

  def front
    @ary[ 5 ]
  end

  def right
    @ary[ 2 ]
  end

end

dice = Dice.new( gets.split.map(&:to_i) )
gets.to_i.times do
  top, front = gets.split.map(&:to_i)
  dice.topface( top )
  dice.frontface( front )
  puts dice.right
end