Programming-Idioms

History of Idiom 43 > diff from v21 to v22

Edit summary for version 22 :

Version 21

2015-09-04, 17:56:17

Version 22

2015-10-29, 14:05:14

Idiom #43 Break outer loop

Look for a negative value v in 2D integer matrix m. Print it and stop searching.

Idiom #43 Break outer loop

Look for a negative value v in 2D integer matrix m. Print it and stop searching.

Code
(print.head.filter(<0).concat)m
Code
(print.head.filter(<0).concat)m
Comments bubble
Haskell's lazy evaluator takes care of breaking all looping when no more searching is needed beyond the first found negative
Comments bubble
Haskell's lazy evaluator takes care of breaking all looping when no more searching is needed beyond the first found negative
Code
OUTER:
for my $row (@m) {
   for $v (@$row) {
      if ($v < 0) {
         print "Negative value found: $v\n";
         last OUTER;
      }
   }
}
Code
OUTER:
for my $row (@m) {
   for $v (@$row) {
      if ($v < 0) {
         print "Negative value found: $v\n";
         last OUTER;
      }
   }
}
Imports
#include <iostream>
Imports
#include <iostream>
Code
auto indices = findNegativeValue (m, 10, 20);
std::cout << m[indices.first][indices.second] << '\n';

std::pair<int, int> findNegativeValue (int **m, int rows, int columns) {
  for (int i = 0; i < rows; ++i) {
    for (int j = 0; j < columns; ++j) {
      if (m[i][j] < 0) return make_pair (i, j);
    }
  }
  throw "No negative value!";
}
Code
auto indices = findNegativeValue (m, 10, 20);
std::cout << m[indices.first][indices.second] << '\n';

std::pair<int, int> findNegativeValue (int **m, int rows, int columns) {
  for (int i = 0; i < rows; ++i) {
    for (int j = 0; j < columns; ++j) {
      if (m[i][j] < 0) return make_pair (i, j);
    }
  }
  throw "No negative value!";
}
Comments bubble
Whenever the code is as complicated as you need to break the outer loop, it is the correct time to add a new function.
Comments bubble
Whenever the code is as complicated as you need to break the outer loop, it is the correct time to add a new function.
Code
mainloop: for(int i=0;i<m.length;i++)
	for(int j=0;j<m[i].length;j++)
		if(m[i][j]<0){
			System.out.println(m[i][j]);
			break mainloop;
		}
Code
mainloop: for(int i=0;i<m.length;i++)
	for(int j=0;j<m[i].length;j++)
		if(m[i][j]<0){
			System.out.println(m[i][j]);
			break mainloop;
		}
Comments bubble
mainloop is a label used to refer to the outer loop.
Comments bubble
mainloop is a label used to refer to the outer loop.
Demo URL
https://ideone.com/GfDlKH
Demo URL
https://ideone.com/GfDlKH