Smart Home - In Action
Here is the latest incarnation of the Smart Home:
I will post the entire source code as soon as I finish with all the code tests.
Here is the latest incarnation of the Smart Home:
I will post the entire source code as soon as I finish with all the code tests.
This is loosely based on th original smart home in hackster.io, but the code is completely different, and it does not have any PubNub hooks, it shows how to build a Smart Home using legos, a Raspberry Pi 3 and mighty Python.
More Photos/Videos:
https://photos.app.goo.gl/D82V1UygVjzEGT4J3 (New Window)Problem: having the following array: [1,3,5,8,9,15], find out which two elements sum 17, Results should be: { a: 8, b: 9 }
Language: JavaScript
Part I, the un-optimized, brute force, and ugly code:
/* So.. s = a + b (keep this in mind) */ function sum2(array, s) { var arrLength = array.length, arrIdx = 0, a = 0, b = 0, controlArray = [0], ctrlArrIdx = 0; /* Now Loop through the main array */ for (arrIdx = 0; arrIdx < arrLength; arrIdx++) { /* Our "a" value will be the element of the array, which we are currently in.. */ a = array[arrIdx]; /* Loop through our "control" array */ for (ctrlArrIdx = 0; ctrlArrIdx < controlArray.length; ctrlArrIdx++) { if (arrIdx === 0) { b = -1; } else { /* Our "b" value is the value of our "control" array.. */ b = controlArray[ctrlArrIdx]; } /* If the formula is true... Success */ if (b >= 0 && a + b === s) { return { a: a, b: b }; } else { /* No match yet, add the number to our control array */ controlArray.push(num); } } } /* If all else fail */ return { a: "Not Found", b: "Not Found" }; } console.log(sum2([1,3,5,8,9,15], 17));
Now the cool, thought out one..
// s = a + b // (therefore) a = s - b function sum2(array, s) { var ctrlArray =[], a = 0, b = 0, results = {a: 'Not Found', b: 'Not Found'}; for (var i = 0; i < array.length; i++) { /* Get out "known" "b" value from the main array */ b = array[i]; /* Apply formula, now we now what value "a" we need! */ var a = s - b; /* if value of "a" is found, then we're set!, otherwise temporarily store so we can scan it on our next interaction */ if (ctrlArray.indexOf(a) >= 0) { results = {a: a, b: b}; break; } else { ctrlArray.push(b); } } return results; } console.log(sum2([1,3,5,8,9,15], 17));
It took me a bit of time to figure out why a second loop is not necessary needed, and also why sorting the array is also not necessarily needed, much cleaner code, and easier to understand. Hope it helps you folks.