You are not logged in. Please login at www.codechef.com to post your questions!

×

Algorithm that searches a value in an 2 dimensional array (matrix).

Searching a value in an 2 dimensional array (matrix).

asked 10 Nov '16, 09:46

rashedcs's gravatar image

2★rashedcs
49761755
accept rate: 4%


include <iostream>

include <algorithm>

include <iterator>

int main() { const size_t N = 3; int a[N][N] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

int value = 9;

auto it = std::find( reinterpret_cast<int *>( a ),
                     reinterpret_cast<int *>( a ) + N * N,
                     value );

if ( it != reinterpret_cast<int *>( a ) + N * N )
{
    size_t n = std::distance( reinterpret_cast<int *>( a ), 
                              it );
    std::cout << "Row = " << n / N << ", Column = " << n % N << std::endl;
}

size_t row = 0;
size_t col = 0;

for ( ; row < N; row++ )
{
    col = 0;
    while ( col < N && a[row][col] != value ) col++;
    if ( col != N ) break;
}

if ( row != N )
{
    std::cout << "Row = " << row << ", Column = " << col << std::endl;
}

return 0;

}

link

answered 10 Nov '16, 10:57

sririshi1424's gravatar image

0★sririshi1424
26
accept rate: 100%

I think it is good tutorial for solving this problem.

link

answered 10 Nov '16, 11:13

rashedcs's gravatar image

2★rashedcs
49761755
accept rate: 4%

edited 10 Nov '16, 11:13

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×846

question asked: 10 Nov '16, 09:46

question was seen: 542 times

last updated: 10 Nov '16, 11:13