Logo

Programming-Idioms

  • PHP
  • Python
  • Scheme
  • Pascal
  • Js

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.

function search(m, x) {
    for (var i = 0; i < m.length; i++) {
        for (var j = 0; j < m[i].length; j++) {
            if (m[i][j] == x) {
                return [i, j];
            }
        }
    }
    return false;
}

Return an array if found, or false if not found.
let search = (x, m) => {
    let i, j, M = m.length, N
    for (i = 0; i < M; ++i) {
        N = m[i].length
        for (j = 0; j < N; ++j)
            if (m[i][j] == x)
                return [i, j]
    }
    return
}
function search($x, array $m): ?array
{
    for ($j = 0; $j < count($m); $j++) {
        if (($i = array_search($x, $m[$j])) !== false) {
            return [$i, $j];
        }
    }

    return null;
}
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.
procedure search(m:T2dMatrix; x:TElement; out i,j:integer);
begin
   for i := 0 to high(m) do
	for j := 0 to high(m[i]) do
            if m[i,j] = x then
               exit;
   i := -1;
   j := -1;
end;
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