My question is, if there is a command/function that gives me the first value for which an expression becomes false?!

For a simulation of several rounds of the game battleships(ger. Schiffe versenken) i want to place the ships. I gave my first ship a position, which is a list of entry of my game board matrix. Now I want a program that again uses my placing algorithm for a new position, which it then compares to the old position. I have tried this with the while and if functions but they either give me several valid positions or they stop when they find the first position that would be valid, but dont print that.


(*game board*)
Matrix[i_, j_] := Alphabet[][[i]]*j;
Spielfeld = Table[Matrix[i, j], {i, 1, 10}, {j, 1, 10}];

vertikal[n_] := Module[{s, z0, position},
   s = RandomInteger[{1, 10}];
   z0 = RandomInteger[{1, 10 - n + 1}];
   position = Table[Spielfeld[[z, s]], {z, z0, z0 + n - 1}];

horizontal[n_] := Module[{z, s0, position},
   z = RandomInteger[{1, 10}];
   s0 = RandomInteger[{1, 10 - n + 1}];
   position = Table[Spielfeld[[z, s]], {s, s0, s0 + n - 1}];

Schlachtschiffsetzen[n_] := Module[{position},
   position = 
    auswahl[n] = If[RandomInteger[1] == 1, vertikal[n], horizontal[n]];
Schlachtschiff = Schlachtschiffsetzen[5];

While[ContainsNone[Schlachtschiffsetzen[4], Schlachtschiff], 
(*my lastest approach to give a new position that doesnt overlap with the other position.
 But I have two problems here. First it gives several valid positions and sometimes doesnt
 give any when the first it generates already overlap*)

  • $\begingroup$ Can you add you code? $\endgroup$
    – Coolwater
    Aug 22, 2019 at 8:22
  • $\begingroup$ Yes I will. Maybe that helps. $\endgroup$ Aug 22, 2019 at 13:45
  • $\begingroup$ Maybe you can try NestWhileList $\endgroup$ Jan 19, 2020 at 14:46

1 Answer 1


Try this


which will try f[1], f[2], f[3], f[4] all of which return True and then f[5] returns False and the code returns 5

Can you adapt that to what you need?

  • $\begingroup$ It seems to be the rigth approach but i cant use it with the ContainsNone function for n being always the same value... $\endgroup$ Aug 22, 2019 at 13:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.