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)


class Dice

  def initialize(dice)
    @top  = dice[0]
    @side   = [ dice[2], dice[1], dice[3], dice[4] ]
    @bottom = dice[5]
  end

  def roll(action)
    action.chars do |str|
      b = @bottom
      u = @top
      case str
      when "N"
        @top   = @side[2]
        @bottom  = @side[0]
        @side[2] = b
        @side[0] = u
      when "E"
        @top   = @side[3]
        @bottom  = @side[1]
        @side[3] = b
        @side[1] = u
      when "S"
        @top   = @side[0]
        @bottom  = @side[2]
        @side[0] = b
        @side[2] = u
      when "W"
        @top   = @side[1]
        @bottom  = @side[3]
        @side[1] = b
        @side[3] = u
      end
    end
  end

  def zzz(top_south)
    i = 0
    loop do
      if top_south[0] == @top
        loop do
          if top_south[1] == @side[1]
            break
          else
            z = @side.shift
            @side.push(z)
          end
        end
      end
      if top_south[1] == @side[1]
        break
      end
      if i < 3
        b = @bottom
        u = @top
        @top = @side[2]
        @bottom = @side[0]
        @side[2] = b
        @side[0] = u
      elsif i > 2
        b = @bottom
        u = @top
        @top = @side[1]
        @bottom = @side[3]
        @side[1] = b
        @side[3] = u
      end
      i += 1
    end
  end

  def top
    @top
  end

  def bottom
    @bottom
  end

  def north
    @side[0]
  end

  def east
    @side[1]
  end

  def south
    @side[2]
  end

  def west
    @side[3]
  end
end

d = Dice.new(gets.split.map(&:to_i))
gets

ARGF.each_line do |line|
  d.zzz(line.split.map(&:to_i))
  puts d.north
end