TransWikia.com

How to store and print the same RandomInteger value that met a condition in a Do loop?

Mathematica Asked by John Matis on March 20, 2021

Let’s suppose that we want to use random guessing to find a matrix G that satisfies the relation F=G.{x,y}:

F={x+y}
Do[If[F == RandomInteger[{-1, 1}, {1, 2}].{x, y}, 
  Print[RandomInteger[{-1, 1}, {1, 2}]]], 100]

Is there any way to print the random matrix that satisfies the If-condition inside a Do-loop, because every next call of RandomInteger changes the matrix? Sorry for my type style, first time here.

One Answer

You should generate random pair once per each loop. E.g.

F = {x + y};
Do[If[F == # . {x, y}, Print[#]] &[
  RandomInteger[{-1, 1}, {1, 2}]], 100]

or, in a more traditional way:

F = {x + y};
Do[pair = RandomInteger[{-1, 1}, {1, 2}]; 
 If[F == pair . {x, y}, Print[pair]], 100]

Correct answer by Roma Lee on March 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP