Created
April 25, 2017 12:07
-
-
Save yvan-sraka/ade8f6384b45ebb13de9ab53980d9725 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
| // ALGORITHME | |
| const max2 = (a, b) => (a > b ? a : b); | |
| // Version iterative | |
| const max_iter = function (T) { | |
| if (!T.length) | |
| throw "Can't use max() an empty array"; | |
| let m = T[0]; | |
| for (let i = 1; i < T.length; i++) | |
| m = max2(m, T[1]); | |
| return m; | |
| } | |
| // Version recursive | |
| const max_rec = function (T) { | |
| if (!T.length) | |
| throw "Can't use max() an empty array"; | |
| if (T.length == 1) | |
| return T[0]; | |
| return max2(T[0], max_rec(T.slice(1, T.length))); | |
| } | |
| // TESTS | |
| console.log(max_rec([2, 5])); | |
| console.log(max_rec([-2, -5, -10])); | |
| // Déroulé des appels recurisf de la fonction max_rec() ; max2 = (a, b) => (a > b : a ? b) | |
| // max_rec([-2, -5, -10]) | |
| // max2(-2, max_rec([-5, -10])) | |
| // max2(-2, max2(-5, max_rec([-10]))) | |
| // max2(-2, max2(-5, -10)) | |
| // max2(-2, -5) | |
| // -2 | |
| console.log(max_rec([2.1])); | |
| console.log(max_rec(["bar", "foo"])); | |
| console.log(max_rec([])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment