読者です 読者をやめる 読者になる 読者になる

SWAP ELEMENTS(CodeEval)

codeeval ruby

CHALLENGE DESCRIPTION:

You are given a list of numbers which is supplemented with positions that have to be swapped.

INPUT SAMPLE:

Your program should accept as its first argument a path to a filename. Input example is the following

1 2 3 4 5 6 7 8 9 : 0-8
1 2 3 4 5 6 7 8 9 10 : 0-1, 1-3

As you can see a colon separates numbers with positions. Positions start with 0. You have to process positions left to right. In the example above (2nd line) first you process 0-1, then 1-3.

OUTPUT SAMPLE:

Print the lists in the following way.

9 2 3 4 5 6 7 8 1
2 4 3 1 5 6 7 8 9 10

My Code

#!/usr/bin/env ruby -w

def swap_elements(numbers, instractions)
  instractions.each do |instraction|
    from, to = instraction.split('-').map(&:to_i)
    numbers[from], numbers[to] = numbers[to], numbers[from]
  end
  numbers.join(' ')
end

ARGF.each_line do |line|
  numbers, instractions = line.chomp.split(':')
  numbers = numbers.split
  instractions = instractions.split(',').map(&:strip)

  puts swap_elements(numbers, instractions)
end