var i,j: integer;
flag:boolean;
[...]
for i := 0 to length(m) * length(m[0]) - 1 do
begin
v := m[i mod length(m), i div length(m)];
if v < 0 then
begin
writeln(v);
break;
end;
end;
for i := 0 to high(m) do
begin
for v in m[i] do
begin
flag := (v < 0);
if flag then
begin
writeln(v);
break;
end;
end;
if flag then
break;
end;
2 Solutions:
1. do it with one loop.
2. Break both loops with a flag.
1. do it with one loop.
2. Break both loops with a flag.
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!";
}
Whenever the code is as complicated as you need to break the outer loop, it is the correct time to add a new function.
edit: The above comment is an opinion and adds nothing to presenting a solution to the stated problem. It is a narrow-minded opinion to think such a statement can apply to every conceivable situation.
edit: The above comment is an opinion and adds nothing to presenting a solution to the stated problem. It is a narrow-minded opinion to think such a statement can apply to every conceivable situation.
matrix = [[1,2,3],[4,-5,6],[7,8,9]]
try:
print(next(i for i in chain.from_iterable(matrix) if i < 0))
except StopIteration:
pass
We make a generator that will return negative values from a list (and use chain.from_iterable(matrix) to lazily extract the values) and only take one value from it with the next function. The generator will not continue until we call next again.
This will raise StopIteration if it doesn't find the value so we need to account for it.
This will raise StopIteration if it doesn't find the value so we need to account for it.
class BreakOuterLoop (Exception): pass
try:
position = None
for row in m:
for column in m[row]:
if m[row][column] == v:
position = (row, column)
raise BreakOuterLoop
except BreakOuterLoop:
pass
This is ugly because the pythonic way to solve this problem would be to refactor so that one doesn't have to break out of multiple loops. See PEP3136
int i,j;
for(i=0;i<sizeof(m)/sizeof(*m);i++)
{
for(j=0;j<sizeof(*m)/sizeof(**m);j++)
{
if(m[i][j]<0)
{
printf("%d\n",m[i][j]);
goto end;
}
}
}
end:
only works if m is allocated statically or on the stack, not if allocated in the heap.
edit: the statement above is misleading. It is referring to the use of sizeof() to set up the loops, and has nothing to do with using goto to break the loop. Using goto to break the loop will work as written, regardless of how the variables are allocated.
edit: the statement above is misleading. It is referring to the use of sizeof() to set up the loops, and has nothing to do with using goto to break the loop. Using goto to break the loop will work as written, regardless of how the variables are allocated.