LoginSignup
0

More than 5 years have passed since last update.

XY-Sort

Last updated at Posted at 2013-09-29

# XY-Sort
# http://nabetani.sakura.ne.jp/hena/ord7xysort/
# http://qiita.com/Nabetani/items/7b08b0eb9ef84d7cfe49
#

TABLE = [
    [ 4, 1, 4, 2, 1, 3 ],
    [ 7, 3, 2, 0, 5, 0 ],
    [ 2, 3, 6, 0, 6, 7 ],
    [ 6, 4, 5, 7, 5, 1 ],
    [ 3, 1, 6, 6, 2, 4 ],
    [ 6, 0, 5, 5, 5, 1 ],
]

ROWS = [*"A".."F"]
COLS = [*"u".."z"]

DISPATCH_TBL = {}
ROWS.each_with_index { |c, i|
    DISPATCH_TBL[c] = [:sort_by_row, i]
}
COLS.each_with_index { |c, i|
    DISPATCH_TBL[c] = [:sort_by_col, i]
}

class Array

    def sort_by_col(col)
        self.sort_by.with_index { |row, i| [row[col], i] }
    end

    def sort_by_row(row)
        self
            .transpose
            .sort_by_col(row)
            .transpose
    end

    def dispatch(cmd)

#       if ROWS.include?(cmd)
#           sort_by_row(ROWS.index(cmd))
#       elsif COLS.include?(label)
#           sort_by_col(COLS.index(cmd))
#       end

        send(*DISPATCH_TBL[cmd])

    end

    def dump
        if $DEBUG
            rowbody = [COLS] + self
            rowhead = [" "] + ROWS
            puts (
                rowbody.map.with_index { |row, i|
                    rowhead[i] + row.join
                }.join("\n")
            )
            puts
        end
    end

end

def xy_sort(command)

    (table = TABLE).tap { |t| t.dump }

    table = command.chars.reduce(table) { |t, cmd|
        t.dispatch(cmd).tap { |t| t.dump }
    }

    table[0].join

end

def test(input, expected)
    result = xy_sort(input)
    print (result == expected) ? "." : "E"
end

test( "AvEx", "305027")       # 0
test( "A", "112344")          # 1
test( "C", "241413")          # 2
test( "F", "134214")          # 3
test( "u", "236067")          # 4
test( "w", "732050")          # 5
test( "y", "414213")          # 6
test( "yx", "732050")         # 7
test( "ux", "236067")         # 8
test( "EF", "131424")         # 9
test( "DF", "134124")         # 10
test( "Au", "055165")         # 11
test( "uA", "023667")         # 12
test( "By", "234114")         # 13
test( "yB", "114342")         # 14
test( "yBy", "357020")        # 15
test( "yByB", "350072")       # 16
test( "AuBvCw", "131244")     # 17
test( "FAuFBvFCw", "300527")  # 18
test( "AuBv", "112344")       # 19
test( "CwDx", "515056")       # 20
test( "FzyE", "324114")       # 21
test( "uAwDyB", "114324")     # 22
test( "zExCvF", "073520")     # 23
test( "uFxEv", "002357")      # 24
test( "DyCwB", "076362")      # 25

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0