TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
saddleback_search.cpp
Go to the documentation of this file.
1
15#include <cassert>
16#include <cstdint>
17#include <iostream>
18#include <vector>
19
23namespace search {
28namespace saddleback {
39std::pair<uint32_t, uint32_t> saddleback(
40 std::vector<std::vector<int32_t>> matrix, int32_t element) {
41 uint32_t left_index = 0;
42 uint32_t right_index = matrix[0].size() - 1; // Start from top right corner
43 while (left_index <
44 matrix.size()) { // Exit once the value of indexes get out of range.
45 if (element ==
46 matrix[left_index]
47 [right_index]) { // If value on this position of matrix is
48 // equal to element, return (row, column).
49 return std::make_pair(left_index + 1, right_index + 1);
50 } else if (element >
51 matrix[left_index]
52 [right_index]) { // Else if value on this position of
53 // matrix is less than the element,
54 // move left.
55 ++left_index;
56 } else if (element <
57 matrix[left_index]
58 [right_index]) { // Else if value on this position of
59 // matrix is greater than the
60 // element, move down.
61 if (!right_index)
62 break;
63 else
64 --right_index;
65 }
66 }
67 return std::make_pair(
68 0, 0); // If the program reaches here, that means one of the index
69 // went out of index, hence no element present.
70}
71} // namespace saddleback
72} // namespace search
73
78static void test() {
79 std::vector<std::vector<int32_t>> matrix = {{1, 10, 100, 1000, 10000},
80 {2, 20, 200, 2000, 20000},
81 {3, 30, 300, 3000, 30000},
82 {4, 40, 400, 4000, 40000},
83 {5, 50, 500, 5000, 50000}};
84
85 std::pair<uint32_t, uint32_t> not_found = std::make_pair(0, 0);
86 std::pair<uint32_t, uint32_t> test_answer;
87 // Test 1
88 std::pair<uint32_t, uint32_t> answer1 =
89 search::saddleback::saddleback(matrix, 123);
90 assert(not_found == answer1);
91 // Test 2
92 answer1 = search::saddleback::saddleback(matrix, 0);
93 assert(not_found == answer1);
94 // Test 3
95 answer1 = search::saddleback::saddleback(matrix, 1);
96 test_answer = std::make_pair(1, 1);
97 assert(test_answer == answer1);
98 // Test 4
99 answer1 = search::saddleback::saddleback(matrix, 50000);
100 test_answer = std::make_pair(5, 5);
101 assert(test_answer == answer1);
102 // Test 5
103 answer1 = search::saddleback::saddleback(matrix, 300);
104 test_answer = std::make_pair(3, 3);
105 assert(test_answer == answer1);
106}
107
112int main() {
113 test(); // execute the tests
114 return 0;
115}
std::vector< std::valarray< T > > matrix
Function for implementing Saddleback Algorithm.
for std::assert
static void test()
Test implementations.
int main()
Main function.