Logo

Programming-Idioms

  • Ada
  • Elixir
  • Lua

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 i,v1 in ipairs(m) do
      for j,v2 in ipairs(v1) do
         if v2 == x then return i,j end
      end
   end
end

Lua functions may return multiple results
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;
def search(m, x) do
  Enum.reduce_while(m, {0, 0}, fn list, {index, _inner_index} ->
    {found?, inner_index} =
      Enum.reduce_while(list, {false, 0}, fn item, {_found?, acc} ->
        if x == item, do: {:halt, {true, acc}}, else: {:cont, {false, acc + 1}}
      end)

    if found?, do: {:halt, {index, inner_index}}, else: {:cont, {index + 1, inner_index}}
  end)
end
#include <string.h>
#include <stdlib.h>
void search(void ***m,void *x,size_t memb_size,int len_x,int len_y,int *i,int *j)
{
	typedef void *m_type[len_x][len_y];
	m_type *m_ref=(m_type*)m;

	for(*i=0;*i<len_x;*i+=1)
	{
		for(*j=0;*j<len_y;*j+=1)
		{
			if(!memcmp((*m_ref)[*i][*j],x,memb_size))
			{
				return;
			}
		}
	}
	*i=*j=-1;
}

m is a matrix containing type (void *) pointing to the data (can be anything)

x is the pointer to the data to look for

memb_size is the size of one element in bytes (to be able to compare anything)

len_x and len_y are the dimensions

i and j are passed by reference and contain the values, or -1 if x was not found, after the function returned.

The typedef is to define the dimensions of the matrix m, this allows for subscript notation

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