Skip to content

Instantly share code, notes, and snippets.

@CodingBobby
Last active December 19, 2019 20:33
Show Gist options
  • Save CodingBobby/fd047874bf891234b207bd0f7bdee085 to your computer and use it in GitHub Desktop.
Save CodingBobby/fd047874bf891234b207bd0f7bdee085 to your computer and use it in GitHub Desktop.
Findet die zweitkleinste Zahl in einem zweidimensionalen Array.
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