I recently got the below question as part of a written interview assessment (it specifically says that I can “feel free to use any available resources”):
// This function should create a 2 dimension array pre-populated
// with zeros. The output appears correct, but it has a bug.
// Explain what's wrong and fix it.
function defaultMatrix(size) { // returns array
// fix me!
var defaultValue = 0;
var row = [];
var matrix = [];
for (var i=0; i < size; i++) { row.push(defaultValue); }
for (var i=0; i < size; i++) { matrix.push(row); }
return matrix;
}
I’ve been looking at it for a couple of hours now, and I just don’t see the “bug”. I’ve tried playing with it on JSFiddle, Googled for the answer, looked on StackOverflow, even emailed the recruiter and asked if “this is a trick question there is no bug” was an acceptable answer. I’m at the point now where knowing the answer is more important than doing anything with the information. What am I missing here?
@tlannoye11 Another example of something that “looks” right at first but does not work as expected is the following:
function abcs() {
var arr = ['a', 'b', 'c', 'd', 'e'];
for (var i = 0; i < arr.length; i++) {
setTimeout(function() {
console.log(arr[i]);
}, 1000);
}
}
abcs();
The intent of the abcs function is to have the letters a through e display one at a time 1 second a part. However, something is not right and causes unexpected results. Can you spot the issue(s) and correct the code? Try to figure it out without actually running the code.
Hummm I can understand what is going wrong, but not WHY. It’s the same result as if row[0][1] was changed before being pushed into matrix, or if we had five declared “row” elements inside the matrix that shared the same value…
Sometimes you actually have to work under those constraints. With web programming we get used to being able to execute our changes immediately, but sometimes you actually have to go through a process of building a web application bundle, moving it around, and restarting an application. If you are working in a compiled language, you don’t want to rebuild your project every time you make a small change. Also, you may be writing a feature that relies on data from sources that you don’t have access to (such as a third party tool or an API that hasn’t been implemented yet).
Now, I’ll post a fix and you tell me what do you think has been changed?
function defaultMatrix(size) {
var defaultValue = 0;
var row = [];
var matrix = [];
for (var i=0; i < size; i++) { row.push(defaultValue); }
for (var i=0; i < size; i++) { matrix.push([...row]); }
return matrix;
}