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: Accepted)

class Dice
  V={N:0,E:1,S:2,W:3}
  def initialize(label)
    @label=label
    @top=1
    @around=[5,3,2,4] # U R D L
    # 右に転がす場合
    # 対角値(レフト,idx3)が上面(top)になる
    # 右(idx1)にもともと上面だった値（top）が入る
    # その対角面(右,idx1)には対角値（合計7になる値）が入る
    # 1 => [5,3,2,4]
    # 4 => [5,1,2,6]
    # 下に転がす場合
    # 1 => [5,3,2,4]
    # 5 => [6,3,1,4]
  end
  def set_position(top,front)
    # 与えられた値（ラベル値）になるようにダイスを回転させる
    # 縦横の回転数を計算して実際に動かす
    top_num=@label.index(top)+1
    front_num=@label.index(front)+1
    # TOP面をあわせる
    if top_num==@top then
    elsif idx=@around.index(top_num)
      rn=self.reverse_vector(idx)
      v=V.key(rn)
      self.move(v)
    elsif
      2.times{self.move("S")}
    end
    # FRONT面を合わせる
    if idx=@around.index(front_num)
      n = case idx
          when 3; 1
          when 2; 0
          when 1; 3
          when 0; 2
          end
      self.turn(n)
    else
      puts "i can not"
    end
  end
  def turn(n)
    # n回右に回転する（TOPは変わらず）
    # n = turn_right * n
    @around.push(@around.shift(n)).flatten!
  end
  def move(v)
    # v = U,R,D,L
    #     N,E,S,W
    #     0,1,2,3
    vn=V[v.to_sym] # 移動方向のインデックス数値
    rn=reverse_vector(vn) # 対角のインデックス数値（2を足す。4を超えていた場合は剰余）
    @top,@around[vn]=@around[rn],@top
    @around[rn]=7-@around[vn]
  end
  def puts_top
    puts @label[@top-1]
  end
  def puts_right
    idx=@around[1]
    puts @label[idx-1]
  end
  def reverse_vector(vn)
    return (vn+2)%4
  end
end
def code_run
  #iS,iL=$stdin.gets.split.map(&:to_i)
  #until ( iN,iX=$stdin.gets.split.map(&:to_i) ) == [0,0] do
  label=$stdin.gets.split.map(&:to_i)
  d=Dice.new(label)
  ($stdin.gets.to_i).times do
    t,f=$stdin.gets.split.map(&:to_i)
    d.set_position(t,f)
    d.puts_right
  end
end

code_run