|
| 1 | +/*************************************************************************************** |
| 2 | +* * |
| 3 | +* CODERBYTE BEGINNER CHALLENGE * |
| 4 | +* * |
| 5 | +* OffLine Minimum * |
| 6 | +* Using the JavaScript language, have the function OffLineMinimum(strArr) take the * |
| 7 | +* strArr parameter being passed which will be an array of integers ranging from * |
| 8 | +* 1...n and the letter "E" and return the correct subset based on the following * |
| 9 | +* rules. The input will be in the following format: ["I","I","E","I",...,"E",...,"I"] * |
| 10 | +* where the I's stand for integers and the E means take out the smallest integer * |
| 11 | +* currently in the whole set. When finished, your program should return that new set * |
| 12 | +* with integers separated by commas. For example: if strArr is * |
| 13 | +* ["5","4","6","E","1","7","E","E","3","2"] then your program should return 4,1,5. * * |
| 14 | +* * |
| 15 | +* SOLUTION * |
| 16 | +* This challenge requires you to repeatedly find the lowerst value in a subset of an * |
| 17 | +* array every time the letter E is found. So to handle this repettiion I am creating * |
| 18 | +* a function that will sort an array in ascending order and return the lowest value. * |
| 19 | +* I will loop through each entry in the array and when I encounter an E then I will * |
| 20 | +* pass a subset of my array starting from position 0 to the location of the E. I * |
| 21 | +* will send this subset to my function to get the lowest value. I will collect all * |
| 22 | +* of the lowest values in an array. When finished I will convert array to string. |
| 23 | +* * |
| 24 | +* Steps for solution * |
| 25 | +* 1) Initialize var subset and min * |
| 26 | +* 2) Create function that sorts an array in asc order and returns lowest value * |
| 27 | +* 3) Store lowest value in an array * |
| 28 | +* 4) Convert array into a string and return as answer * |
| 29 | +* * |
| 30 | +***************************************************************************************/ |
| 31 | + |
| 32 | +function OffLineMinimum(strArr) { |
| 33 | + |
| 34 | + var subset = [], min = 0; |
| 35 | + function findMin (arr) { return arr.sort(function (a,b) {return Number(a)-Number(b);})[0]; } |
| 36 | + for (var i=0;i<strArr.length;i++) { |
| 37 | + if (strArr[i] == "E") { |
| 38 | + min = findMin(strArr.slice(0,i)); |
| 39 | + minIndex = strArr.slice(0,i).indexOf(min) |
| 40 | + subset.push(Number(min)); |
| 41 | + strArr = strArr.slice(0,minIndex).concat(strArr.slice(minIndex+1,i)).concat(strArr.slice(i+1)); |
| 42 | + i-=2; |
| 43 | + } |
| 44 | + } |
| 45 | + return subset.join(","); |
| 46 | + |
| 47 | +} |
0 commit comments