Created
May 17, 2021 02:21
-
-
Save Verdagon/cc9970e0e3742b3e7d670af6a315d8f9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Idiom #20 - Return two values | |
// Implement a function search which looks for item x in a 2D matrix m. | |
// Return indices i, j of the matching cell. | |
// Think of the most idiomatic way in the language to return | |
// the two values at the same time. | |
fn main() export { | |
m = [][ [][1, 2, 3], [][4, 5, 6], [][7, 8, 9] ]; | |
to_search = 4; | |
found! = false; | |
eachI &m (i, m1){ | |
eachI m1 (j, m2){ | |
if (m2 == to_search) { | |
mut found = true; | |
println("The number " + to_search + " was found on row " + i + " and column " + j); | |
} | |
} | |
} | |
if (not found) { | |
println("The number " + to_search + " was not found!"); | |
} | |
// => The number 4 was found on row 1 and column 0 | |
// searching in a range (s is number to search): | |
s! = 1; | |
while (s <= 11) { | |
mut found = false; | |
eachI &m (i, m1){ | |
eachI m1 (j, m2){ | |
if (m2 == s) { | |
mut found = true; | |
println("The number " + s + " was found on row " + i + " and column " + j); | |
} | |
} | |
} | |
if (not found) { | |
println("The number " + s + " was not found!"); | |
} | |
mut s = s + 2; | |
} | |
// => | |
// The number 1 was found on row 0 and column 0 | |
// The number 3 was found on row 0 and column 2 | |
// The number 5 was found on row 1 and column 1 | |
// The number 7 was found on row 2 and column 0 | |
// The number 9 was found on row 2 and column 2 | |
// The number 11 was not found! | |
// Calling a search function: | |
(found2, ix1, ix2) = search(&m, to_search); | |
if (found2) { | |
println("The number " + to_search + " was found on " + ix1 + ", " + ix2); | |
} else { | |
println("The number " + to_search + " was not found!"); | |
} | |
} | |
// fn search(m [3 * [3 * int]], s int) infer-ret { | |
// fn search(m &Array<mut, Array<mut, int>>, s int) Array<mut, int> { | |
// fn search(m &Array<mut, Array<mut, int>>, s int) infer-ret { | |
fn search(m &[<mut> 3 * [<mut> 3 * int]], s int) infer-ret { | |
//eachI m (i, m1){ | |
//eachI m1 (j, val){ | |
//if (val == s) { | |
//ret [true, i, j]; | |
//} | |
//} | |
//} | |
ret [false, 0, 0]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment