Ad

Description:

A board represents square sized table with columns named with numbers and rows named with chars as following:

| | 1 | 2 | 3 |...
|a|   |   |   |...
|b|   |   |   |...
|c|   |   |   |...
.
.
.

Each field is corresponding to specific coordinate this way: a1 -> (0, 0); a2 -> (0, 1), ..., c2 -> (2, 1), c3 -> (2, 2) ...

Size of square board will be less or equal english alphabet's letter count i.e. <= 26. Let's consider that passed parameter is correct and have a value within 'a1'..'z26'.

Your task is to write a function which accepts a field parameter in string representation for example 'a1' and return a tuple respresenting a corresponding coordinate - (rowIndex, columnIndex), e.g. if there was passed 'c1' then result should be (2, 0).

Changes

This version has two advantages over the original. First, and primary, it is written in Clojure, so is much more flexible. Second, it can take uppercase letters as well, and convert them to lowercase letters (for robustness).

Code
Diff
  • (ns ordoflammae.coordinate
      (:require [clojure.string :as str]))
    
    (defn field->coordinate
      [field]
      (let [field (str/lower-case field)
            rowChar (first field)
            col (Integer. (apply str (rest field)))]
        [(- (int rowChar) (int \a)) (dec col)]))
    • import re
    • def field_to_coordinate(field):
    • # Compute a coordinate which represents specified `field`,
    • # i.e. if field = 'd2' returned value should be [3, 1]
    • x, y = re.search(r"([^\d])(\d+)", field).groups()
    • return (ord(x) - 97, int(y) - 1)
    • (ns ordoflammae.coordinate
    • (:require [clojure.string :as str]))
    • (defn field->coordinate
    • [field]
    • (let [field (str/lower-case field)
    • rowChar (first field)
    • col (Integer. (apply str (rest field)))]
    • [(- (int rowChar) (int \a)) (dec col)]))