This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
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.
- Ada
- C
- Caml
- Clojure
- C++
- C++
- C#
- D
- Dart
- Elixir
- Erlang
- Fortran
- Go
- Haskell
- JS
- JS
- Java
- Java
- Kotlin
- Lisp
- Lua
- Obj-C
- PHP
- Pascal
- Perl
- Python
- Python
- Ruby
- Rust
- Scala
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;
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
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
module Arr = Bigarray.Array2
let search array value =
let x_max = Arr.dim1 array in
let y_max = Arr.dim2 array in
let rec loop x y =
(* End of array *)
if x = x_max then
raise Not_found
(* End of row, go to next *)
else if y = y_max then
loop (x+1) 0
else
(* If found, return it *)
if array.{x,y} = value then
(x,y)
(* Otherwise go to next col *)
else
loop x (y+1)
in
loop 0 0
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.
The elements can be accessed via returnValue.first and returnValue.second.
(int, int) Search(int[,] m, int x)
{
for (var i = 0; i <= m.GetUpperBound(0); i++)
for (var j = 0; j <= m.GetUpperBound(1); j++)
if (m[i, j] == x)
return (i, j);
return (-1, -1);
}
In C# 7.0 and higher, you can return implicit tuples
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
-spec search(T, [[T]]) -> {pos_integer(), pos_integer()}.
search(X, M) -> search(X, M, 1).
search(_, [], _) -> throw(notfound);
search(X, [R|Rs], RN) ->
case search_row(X, R) of
notfound -> search(X, Rs, RN+1);
CN -> {RN, CN}
end.
search_row(X, Row) -> search_row(X, Row, 1).
search_row(_, [], _) -> notfound;
search_row(X, [X|_], CN) -> CN;
search_row(X, [_|Elems], CN) -> search_row(X, Elems, CN+1).
M is represented as a list of rows. Not using any function from the lists module this time.
func search(m [][]int, x int) (bool, int, int) {
for i := range m {
for j, v := range m[i] {
if v == x {
return true, i, j
}
}
}
return false, 0, 0
}
Go functions may return multiple values.
This function returns 3 values : one to indicate if x was found or not, and two for the coordinates.
This function returns 3 values : one to indicate if x was found or not, and two for the coordinates.
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.
static class Position{
int i;
int j;
}
Position search(int[][] m, int x){
for(int i=0;i<m.length;i++)
for(int j=0;j<m[i].length;j++)
if(m[i][j] == x){
Position pos= new Position();
pos.i = i;
pos.j = j;
return pos;
}
return null;
}
A Java method returns 0 or 1 value only. So we have to create a custom class Position to hold the two values to return.
NSIndexPath *search(NSArray *m,id x) {
NSUInteger j,i;
for (i=0;i<m.count;i++) {
if ((j=[m[i] indexOfObject:x])!=NSNotFound)
return [NSIndexPath indexPathWithIndexes:&i length:2];
}
return nil;
}
In practice, it would not be implemented as a function, but as a new method of NSArray. Note we read the indices directly from the stack; with really weird architectures might be safer to use ij[2] instead
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(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.