Last active
December 19, 2019 20:33
-
-
Save CodingBobby/fd047874bf891234b207bd0f7bdee085 to your computer and use it in GitHub Desktop.
Findet die zweitkleinste Zahl in einem zweidimensionalen Array.
This file contains 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
let arr = [[1, 3, 4, 2], [5, 3, 2], [1, 1, 3, 7]] | |
let lowVal = arr[0][0] | |
let secLowVal = arr[0][0] | |
let preVal = arr[0][0] | |
for(let i=0; i<arr.length; i++) { | |
for(let j=0; j<arr[i].length; j++) { | |
// finden der kleinsten Zahl, die zuvor gefundene Zahl wird zwischengespeichert | |
if(arr[i][j] < lowVal) { | |
preVal = lowVal | |
lowVal = arr[i][j] | |
} | |
// dieser Teil wird gebraucht, um die folgenden Zahlen einzubeziehen, | |
// wenn lowVal bereits den kleinsten Wert angenommen hat | |
if(arr[i][j] < secLowVal && arr[i][j] > lowVal || secLowVal == lowVal) { | |
secLowVal = arr[i][j] | |
} | |
// dieser Teil wird gebraucht, falls die tatsächliche, zweitkleinste Zahl | |
// zuletzt dann gesehen wird, wenn lowVal noch nicht kleiner als diese geworden ist | |
if(preVal < secLowVal && preVal > lowVal) { | |
secLowVal = preVal | |
} | |
// logging in JavaScript | |
console.log(`num: ${arr[i][j]}, low: ${lowVal}, sec: ${secLowVal}`) | |
} | |
} | |
// secLowVal is jetzt die zweitkleinste Zahl |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment