Logo

Programming-Idioms

  • Lisp
  • C++
  • Python
  • Python

Idiom #20 Return two values

Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.

def search(m, x):
    for idx, item in enumerate(m):
        if x in item:
            return idx, item.index(x)
def search(x, m):
    for i, M in enumerate(m):
        for j, N in enumerate(M):
            if N == x: return (i, j)

This will return a tuple.
(defun mysearch (x m)
  (loop for i below (array-dimension m 0)
        do (loop for j below (array-dimension m 1)
                 when (eql x (aref m i j))
                 do (return-from my-search
                                 (values i j)))))
bool _search(const Matrix& _m, const float _x, size_t* const out_i, size_t* const out_j) {
  for (size_t j = 0; j < _m.rows; j++) {
    for (size_t i = 0; i < _m.cols; i++) {
      if (_m.at(i, j) == _x) {
         *out_i = i;
         *out_j = j;
         return true;
      }
    }
  }
  return false;
}
#include <utility>
template<typename T, size_t len_x, size_t len_y>
std::pair<size_t, size_t> search (const T (&m)[len_x][len_y], const T &x) {
    for(size_t pos_x = 0; pos_x < len_x; ++pos_x) {
        for(size_t pos_y = 0; pos_y < len_y; ++pos_y) {
            if(m[pos_x][pos_y] == x) {
                return std::pair<size_t, size_t>(pos_x, pos_y);
            }
        }
    }

    // return an invalid value if not found
    return std::pair<size_t, size_t>(len_x, len_y);
}

This tries to be similar to the C variant. In a real world program the 2D matrix should offer an iterator.

The elements can be accessed via returnValue.first and returnValue.second.
type Matrix is array (Positive range <>, Positive range <>) of Integer;

function Search (M : Matrix; X : Integer; I, J : out Integer) return Boolean is
begin
   for K in M'Range (1) loop
      for L in M'Range (2) loop
         if M (K, L) = X then
            I := K;
            J := L;
            return True;
         end if;    
      end loop;
   end loop;

   return False;
end Search;

New implementation...
< >
programming-idioms.org