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)

MODE = "stdio"
require 'matrix'
include Math
line = Array.new

if(defined? MODE)
  line = STDIN.read.split("\n")
else
  tmp = '1 2 3 4 5 6
  3
  6 5
  1 3
  3 2'.split("\n")
  tmp.each{|s|
    line << s.strip
  }
end
class Dice
  attr_accessor :top, :front, :right, :left, :back, :bottom
  def initialize(arr)
    @top = arr[0]
    @front = arr[1]
    @right = arr[2]
    @left = arr[3]
    @back = arr[4]
    @bottom = arr[5]
  end

  def roll(s)
    case s
    when "E"
      @top, @right, @bottom, @left = @left,@top, @right, @bottom
    when "W"
      @top, @right, @bottom, @left = @right, @bottom, @left, @top
    when "N"
      @top, @back , @bottom, @front = @front,@top, @back , @bottom
    when "S"
      @top, @back , @bottom, @front = @back , @bottom, @front,@top
    end
    [@top, @front, @right, @left, @back, @bottom]
  end

  def rolls(s)
    s.chars.each do|s|
      roll(s)
    end
    [@top, @front, @right, @left, @back, @bottom]
  end

end

arr = line[0].split(" ").map(&:to_i)
num = line[1].to_i
cmd = ["E","W","N","S"]
  
dice = Dice.new(arr)
(2..num+1).each do |n|
  top,front = line[n].split(" ").map(&:to_i)
  while true
    dice.roll(cmd.sample)
    break if(dice.top == top) && (dice.front == front)
  end
  puts dice.right
end