Front end cashier Interview Questions
front end cashier interview questions shared by candidates
Top Interview Questions
What is a JavaScript callback function? 5 Answers5 vote down star 4 I understand passing in a function to another function as a callback and having it execute, but I'm not understanding the best implementation to do that. I'm looking for a very basic example, like this: var myCallBackExample = { myFirstFunction : function( param1, param2, callback ) { // Do something with param1 and param2. if ( arguments.length == 3 ) { // Execute callback function. // What is the "best" way to do this? } }, mySecondFunction : function() { myFirstFunction( false, true, function() { // When this anonymous function is called, execute it. }); } }; In myFirstFunction, if I do return new callback(), then it works and executes the anonymous function, but that doesn't seem like the correct approach to me. I don't think Bloomberg is a very good company. I am an excellent web developer and have gotten multiple offers from other companies with big names, but was rejected by Bloomberg. They are too demanding during the job interview and it becomes a game of how well you can interview as opposed to how talented an employee you are and how much you can contribute to the growth of the company. A callback function is a piece of JavaScript code that executes after the main function that the callback is attached to executes successfully. Show More Responses udaykanth, I would say that a .forEach() would be the most common and most basic use of a callback function. I'm just writing this to help anyone that might have a hard time thinking up a quick example if the come across this question themselves. Example: var numArray = [ 1, 2, 3 ] ; numArray.forEach( function( i ) { console.log( arr[ i - 1 ] ) } ) ; // logs out // 1 // 2 // 3 Is there a front end role at bloomberg. I guess your position must have been labelled software dev right? altho ur a dront end dev |
Front End Developer at GCI was asked...
How to center a 200px x 200px div to the center of the screen? 2 AnswersProvide top and left 50% then off set the div with -100px margin top and left. A more scaleable solution would be to use transform: translate(-50%, -50%) to make it not matter what size the div is. <div> <div> Inner </div> <div> .outer { width: 100vw; height: 100vh; position: relative; } .inner{ width: 200px; height: 200px; position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; }</div></div> |
As a designer, did I think I would get bored with coding and troubleshooting? 1 AnswerI let them know that while design is a creative field, I have always been interested in designing for the user, and coding is no different. Whether creating a design or writing code the interesting part to me was the end result for the user. |
Say there was a function that took 1 second to execute and you needed to run this function 10 million times, how would you cut down on the execution time? 1 AnswerBuild a system that would run the functions concurrently. |
Front-End Web Developer at IXL Learning was asked...
Given a number n where n+1 and n-1 are prime, prove n is divisible by 6 1 Answern+1 is prime, n+2 is prime... all prime numbers are odd, so n must be even (i.e., divisible by 2) in any set of 3 numbers (consider 1,2,3 or 4,5,6 or 20,21,22) at least one number is divisible by 3. since n+1 and n+2 can't be divisible by anything, n must be divisible by 3. therefore n is div by 6 |
Front End Web Developer at LinkedIn was asked...
If we wanted to implement a method of tracking every click that the user made on the site, how would we want to do this? 1 AnswerPlace a JavaScript event listener for all clicks at the document level. Perform actions based on the details of the click. This problem had multiple branches and sub-questions, but the gist is that you would want to capture the events as they bubbled back up to the document level. There are other acceptable answers to this question. |
UI Front End Developer at AT&T was asked...
What is== and === operator? 1 Answer== returns a Boolean true if both the operands are equal. === this is the strict equal operator and only returns a Boolean true if both the operands are equal and of the same type. |
Front End Engineer at Facebook was asked...
Given an input array and another array that describes a new index for each element, mutate the input array so that each element ends up in their new index. Discuss the runtime of the algorithm and how you can be sure there won't be any infinite loops. 26 Answerspublic static void permute(String[] a, int[] b) { int n = a.length; for (int i = 0; i < n; i++) { while (b[i] != i) { swap(i, b[i], a, b); } for (int j = 0; j < n; j++) { System.out.print(a[j]); } System.out.println(); } } public static void swap(int i, int j, String[] a, int[] b) { int bt = b[j]; b[j] = b[i]; b[i] = bt; String at = a[j]; a[j] = a[i]; a[i] = at; } // you know there aren't infinite loops because the algorithm reduces the number of misplaced elements at each step Javascript Version: function mutate(input, specArr) { var visited = []; specArr.forEach(function(newIdx, i) { var tmp; visited.push(newIdx); if (visited.indexOf(i) < 0) { tmp = input[i]; input[i] = input[newIdx]; input[newIdx] = tmp; } }); } Trick is to keep track of visited indices and make sure you're not performing unecessary replacements. Run time is THETA(n) as indexOf is a constant-time operation since an array in javascript is simply an object (see http://es5.github.io/#x15.4.4.14 ). function repositionElements(arr, indices) { // assert(arr.length === indices.length) var moved = []; for (var i = 0; i < arr.length; i++) { moved.push(false); } var moveFrom, moveTo, itemToMove; for (moveFrom = 0; moveFrom < arr.length; moveFrom++) { itemToMove = arr[moveFrom]; while (!moved[moveFrom]) { moveTo = indices[moveFrom]; var tmpItem = arr[moveTo]; arr[moveTo] = itemToMove; itemToMove = tmpItem; moved[moveFrom] = true; moveFrom = moveTo; } } return arr; } var arr = ["a", "b", "c", "d", "e", "f"], indices = [2, 3, 4, 0, 5, 1]; repositionElements(arr, indices); // returns: ["d", "f", "a", "b", "c", "e"] Show More Responses function reposition(arr, indices) { var newArr = []; // I'm not sure if extra space is allowed. If it is, the solution should be this simple. for(var i = 0; i < arr.length; ++i) { var newIndex = indices[i]; newArr[newIndex] = arr[i]; } return newArr; } var arr = ["a", "b", "c", "d", "e", "f"]; var indices = [2, 3, 4, 0, 5, 1]; reposition(arr, indices); // returns: ["d", "f", "a", "b", "c", "e"] Essentially the same as Anh's answer but less code, assuming ES5 is available var arr = ["a","b","c","d","e","f"]; var indices = [2, 3, 4, 0, 5, 1]; arr = indices.map(function (item, index) { return arr[indices.indexOf(index)]; }); //Bringing 2 UNIDEAL solutions var A = ['a', 'b', 'c', 'd', 'e', 'f']; var B = [4, 3, 2, 5, 1, 0]; //PROBLEM we need a copy of an A to get a proper base index of an element in the sort function var BaseA = A.concat([]); A.sort(function(a, b){ return A.indexOf(a) < B.indexOf(BaseA.indexOf(a)); }); alert[A); //OR We'll just add up to A sorted values and then cut off the tail, I believe it's //almost same performace as to create new array but well, it does mutate A //so is it "Done is better then perfect" after all? :) for(var i = 0, l = B.length; i < l; i++){ A.push(A.splice(B[i], 1, undefined).pop()) } A.splice(0, B.length); alert[A); void swap(int a[],int b[], int i,int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; temp = b[i]; b[i] = b[j]; b[j] = temp ; } void mutate(int a[], int b[], int n) { // solutions 1 . we can sort an array b and while doing that we will // adjust the A[] elements as well // but it is going to be nlogn // Solution 2: swap the elements of b[] ( together with a[] elements) until the number in the b[i] matches the index i then move on to i+1 // for each swap we are placing one item in the right place. // so the complexity would be O(n) for(int i=0;i= n) { cout << "Index out of bound " << b[i] <<< endl; break; } if(i != b[i]) // this may go in infinite loop, if the indices are not good in b like two 0s in the b[] { if(b[i] == b[b[i]]) { cout << "Infinite Loop Detected for the index " << b[i] << endl; break; } swap(a,b,i,b[i]); } else { i++; } } } var assert = require('assert'); var arr = ['a','b','c','d','e','f','g', 'a']; var indexes = [2,1,0,3,4,5,7,6] var mutate = function mutate(arr, ind){ var swapped = {}; indexes.forEach(function(nI, i){ var newEl, el; el = arr[i]; arr[i] = swapped[nI] || arr[nI]; swapped[i] = el; }); }; mutate(arr, indexes) assert.deepEqual(arr, ['c','b','a','d','e','f','a', 'g']); function remap(arr1, arr2){ var tmp1 = arr1.slice(); arr2.map(function(newIdx, realIdx){ arr1[newIdx] = tmp1[realIdx]; }); } Working off of Travis' answer, but removing the need for a new array: function swap(arr, idx1, idx2) { var temp = arr[idx1]; arr[idx1] = arr[idx2]; arr[idx2] = temp; } function reposition(input, indices) { indices.forEach(function(newIdx, i) { if (indices.indexOf(i) > i) { swap(input, i, newIdx) } }); } Here's my take on this, though I think my approach is cheating a little bit since I'm mutating, but not directly in place. It does add a little space complexity since I'm adding a new array, but there are no infinite loop problems and the runtime is just O(n) (I think...I'm really bad at big O notation calculation). function mutateArray(arr,indexes) { var newArr = []; indexes.forEach((ix) => { newArr.push(arr[ix]); }); arr.splice(0).push.apply(arr,newArr); } OK, and after seeing that there's some confusion amongst expected outputs, I've updated my implementation based on the other take on the expected output. This version assumes that each index in the provided index array is the index value of where the element is in the starting array. So if the value at indexes[0] = 3, that would mean the first value in the output would be originalArray[3]; function mutateArray(arr,indexes) { var newArr = new Array(arr.length); indexes.forEach((ix, i) => { newArr[ix] = arr[i]; }); arr.splice(0).push.apply(arr,newArr); } var original = [2, 3, 1, 6, 4]; var ixes = [1, 2, 0, 4, 3]; expected results: [1, 2, 3, 4, 6] For clarity, the other variant is in my answer above. That assumes that the value of each element in the indexes array represents the index of the value of the original array. So in the example above, the output would be [3, 1, 2, 4, 6]. Apparently a common twist is to then ask the interviewee to do this without a new array. So that's worth practicing too. Show More Responses OK, and here's my in place version. It could definitely be improved since I just wrote it using the bubble sort algorithm. Any other sorting algorithm would work just fine too. Basically it works by sorting the index array and every time something in the index array is moved, it moves the same elements on the original array. function mutateArray(arr,indexes) { var swapped = true; while(swapped) { swapped = false; for(var i = 1; i indexes[i]) { swap(arr,i-1,indexes[i-1]); swap(indexes, i-1, indexes[i-1]); swapped = true; } } } } function swap(arr, oldIx, newIx) { var temp = arr[newIx]; arr[newIx] = arr[oldIx]; arr[oldIx] = temp; } An example: var arr = [5,2,1,8,9,1]; var indexes = [2,4,1,0,3,5]; var expectedResult = [8,1,5,9,2,1]; function changeArr(arr,indArr) { var i, retArr = []; for( i = 0; i Simple solution using .map() & ES6: const inputArray = ["one", "two", "three", "four", "five", "six"] const indexArray = [2, 1, 3, 5, 4, 6] function mutate(input, index) { const newArray = index.map(i => input[i - 1]) return newArray } // output: ["two", "one", "three", "five", "four", "six"] or if you truly want to mutate the array rather than outputting a new array: let inputArray = ["one", "two", "three", "four", "five", "six"] const indexArray = [2, 1, 3, 5, 4, 6] inputArray = indexArray.map(i => inputArray[i-1]) // output: ["two", "one", "three", "five", "four", "six"] const sortBy = (inputArr, idxArr) => idxArr.reduce((acc, x) => acc.concat(inputArr[x]), []) For all of the answer using map, and visited arrays, just to say that you are creating a new array, and from the word "mutate" I assume they don't want any extra space being used at all (also it takes longer) My solution using ES6 is: function mutate(input, indices) { const swap = (i, j) => { let tmp = input[i]; input[i] = input[j]; input[j] = tmp; }; indices.forEach((newIndex, i) => swap(newIndex, i)); return input; } Also for those using indexOf that's an extra O(n) you're using there! let input = [1,2,3,4,5]; let newIndex = [3,1,0,4,2]; function transform(input, newIndex) { let res = []; for (let i = 0; i < input.length; i++) { let index= newIndex[i]; let val = input[i]; res[index] = val; } return res; } function transform2(input, newIndex) { let i = 0; while (i < input.length) { if (i == newIndex[i]) { i++; } else { swap(input, i, newIndex[i]); swap(newIndex, i, newIndex[i]); } } } function swap(arr, i, j) { let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } function sort(a,b){ for(let i=0, l=b.length; i Show More Responses function correctTheOrder(arr, indices) { return arr.map((noUse, index) => { return arr[indices.indexOf(index)] }) } // Time complexity = O(n2) // Space complexity = O(n) function correctTheOrder2(arr, indices) { let i = 0; while (i < arr.length) { if (indices[i] === i) { i++; } else { let temp = arr[i]; arr[i] = arr[indices[i]]; arr[indices[i]] = temp; temp = indices[i]; indices[i] = indices[indices[i]]; indices[temp] = temp; } } return arr; } // Time complexity = O(n) // Space complexity = O(1) O(n) time and O(1) solution. Only issue is input can't be negatives or zeroes. function changeIdxO1(A,I) { for (let i = 0; i 0) { [A[next], A[current]] = [A[current], A[next]]; [I[next], I[current]] = [I[current], I[next]]; A[next] = -A[next]; next = I[current]; } } for (let i = 0; i < A.length; i++) A[i] = Math.abs(A[i]); return A; } const updatePositions = (A,B) => B.map(item => A[item]) Would that be enough? One or more comments have been removed. |
Front End Engineer at Facebook was asked...
Given input: // could be potentially more than 3 keys in the object above items=[ {color: 'red', type: 'tv', age: 18}, {color: 'silver', type: 'phone', age: 20} ... ] excludes=[ {k: 'color', v: 'silver'}, {k: 'type', v: 'tv'}, .... ] function excludeItems(items, excludes) { excludes.forEach(pair => { items=items.filter(item => item[pair.k] === item[pair.v]); }); return items; } 1. Describe what this function is doing... 2. What is wrong with that function ? 3. How would you optimize it ? 23 Answers1. excluding the items according to "excludes" array 2. (a) it's mutable. (b) it runs in a O(n^2) complexity 3. first turn "excludes" array into a map like so: excludes = { color: ['silver', 'gold' ...], type: ['tv', 'phone' ...] } then, rewrite the function like so: function excludeItems(items, excludes) { const newItems = []; items.forEach(item => { let isExcluded = false; for (let key in item) { if (excludes[key].indexOf(item[key]) !== -1) { isExcluded = true; break; } } if (!isExcluded) { newItems.push(item); } }); return newItems; } Another solution without remapping the exclusions. function excludeItems(items, excludes) { return items.filter((item) => { return excludes.filter((exclusion) => { return item[exclusion.k] === exclusion.v }).length === 0; }) } I guess there's a typo in the question? I don't really get the purpose of "item[pair.k] === item[pair.v]" Show More Responses function excludeItems(items, excludes) { return excludes.reduce((arr, pair) => { arr.push(items.filter(item => item[pair.k] === pair.v)); return arr; },[]); } If the objetive is exclude the elements using the excludes filters the function should be: function excludeItems(items, excludes) { excludes.forEach(pair => { items = items.filter(item => item[pair.k] !== pair.v); }); return items; } This solution will give much faster and immutable result. You can test with performance.now items.reduce((allItems, item) => { if(!excludes.some(exclude=>item[exclude.k] === exclude.v)){ allItems.push(item); } return allItems; }, []); you can map the exclude array into objects of object to make it run in constant time. var excludes = turnIntoMap(excludes); function turnIntoMap(arr){ var hash = {}; arr.forEach(function(val){ if(hash[val[k]]){ hash[val[k]][val[v]] = 1 } else { hash[val[k]] = {}; hash[val[k]][val[v]] = 1 } }); } items.filter(function(item){ for(var key in item){ if(excludes[key]){ if(excludes[key][item[key]]){ return false; } } } return true; }); let newItems = items.reduce((acc, item) => { let result = excludes.some(exclude => item[exclude['k']] === exclude['v']); if (!result) { acc.push(item); } return acc; }, []); console.log(newItems); I agree with converting the excludes to an object, but in order to get linear performance that doesn't depend on the number of excluded things, you have to concatenate the k and v into one value to be used as the key in the object: let excludesObject = {}; excludes.forEach(pair => excludesObject[`${pair.k}_${pair.v}`] = true); Then you can check if an item should be excluded in O(k) time where k is the number of keys in an item. And the whole thing will run in O(nk) where n is the number of items. // if there is some key which is found in the excludesObject, the filter will return false items = items.filter(item => !Object.keys(item).some(key => excludesObject[`${key}_${item[key]}`]); ); Facebook, hire me! lol build excludes table as follows map = { color: { red: 1, green:1 }, type: { tv: 1 } } Solution: function excludeItems(items, excludes) { let map = {}; for (let exclude of excludes) { let { k, v } = exclude; if (map[k] != null) { map[k][v] = 1; } else { map[k] = { [v]: 1 }; } } return items.filter(item => { for (let key in item) { if (map[key] && map[key][item[key]]) { return false; } } return true; }); } const items = [ {color: 'black', type: 'phone', age: 20}, {color: 'red', type: 'tv', age: 18}, {color: 'silver', type: 'tv', age: 20}, ]; const excludes = [ {k: 'type', v: 'tv'}, {k: 'color', v: 'silver'}, ]; function excludeItems(items, excludes) { excludesObject = {}; excludes.forEach(pair => { excludesObject[pair.k] = pair.v; }); items = items.filter(item => { for (key in excludesObject) { if (item[key] === excludesObject[key]) { return false; }; } return true; }); return items; } console.log(excludeItems(items, excludes)); function excludeItems(items, excludes) { const map = new Map( excludes.map( el => [ el.v, el.k ] ) ); return items.filter(item => ( !Object.keys(item).some(key => map.has(item[key]) && map.get(item[key]) === key) )); } 1. Excluding any items that is has an element in the "excludes" collection. 2. (a) "filter" returns anything that is true in the conditional. This is doing the opposite. (b) it's checking item[pair.v], which will never return a value. It should be "item[pair.k] !== pair.v" 3. Currently, it's O(n^2). For each excluding element, it's traversing through the entire 'items' list. A start would be to condense the "excludes" object by creating lists. Ex: excludes = {['k': 'color', 'v': ['blue', 'red', 'purple']] "item[pair.k].includes(pair.v)" ***NOTE: (this is still O(n^2), but it's more efficient than before)*** Not sure how to condense it down to O(n log(n)) Show More Responses "excludes table as follows" answer from above can be improved if replace the constructed object (aka excludes table) with Set. 1. fixing a bug in the filter function. function excludeItems(items, excludes) { excludes.forEach(pair => { items = items.filter(item =>item[pair.k] !== pair.v); }); return items; } 2. optimizing... the function is O(n^2). still we can optimize in worst case O(n^2) but , as soon as it finds excluded condition meets, no need to see remaining excluded pairs. just jumping to next item. Array.forEach or Array.map does not allow bread in the middle of loop while for sentence does. So, I replaved Array.forEach to 'for' sentence. function excludeItems(items, excludes) { let result = items.filter(item => { for(let e = 0; e < excludes.length; e++) { let pair = excludes[e]; if((item[pair.k] === pair.v)) { return false; // moving to next item. no need to see next excluded element } } return true; }); return result; } (fixing typo) 1. fixing a bug in the filter function. function excludeItems(items, excludes) { excludes.forEach(pair => { items = items.filter(item =>item[pair.k] !== pair.v); }); return items; } 2. optimizing... the function is O(n^2). still we can optimize in worst case O(n^2) but , as soon as it finds an excluded condition meets, no need to see remaining excluded pairs. just jumping to next item. Array.forEach or Array.map does not allow 'break' in the middle of loop while regular FOR sentence does. So, I replaced Array.forEach with FOR sentence. function excludeItems(items, excludes) { let result = items.filter(item => { for(let e = 0; e < excludes.length; e++) { let pair = excludes[e]; if((item[pair.k] === pair.v)) { return false; // moving to next item. no need to see next excluded element } } return true; }); return result; } I got this problem to in my video interview, The way I solved the problem is re-estrcuturing the excludes array with and Object that the keys are the attributes of the items and the value is a set I was told that the number of attributes of one item is always less than 10 so the overall complexity of my solution was O(10*n) function excludeItems(items, excludes) { let excludesMap = excludes.reduce((entry, result)=>{ entry[result.k + result.v] = true; return entry; },{}); return items.reduce( (result, item) => { let updatedObject = Object.keys(item).reduce( (result,key) => { if(!excludesMap[key + item[key]]){ result[key] = item[key] } return result; }, {}) result.push(updatedObject) return result; }, []) } function excludeItems(items, excludes) { const keyFormat =(key,value)=>`${key}_${value}`; excludes = excludes.reduce((result, exclude)=>{ result[keyFormat(exclude['k'], exclude['v'])] = true; return result; },{}); return items.filter((item)=>{ for(let key of Object.keys(item)){ if(excludes[keyFormat(key,item[key])]) return false; } return true; }); } const items = [{ color: 'red', type: 'tv', age: 18 }, { color: 'silver', type: 'phone', age: 20 }]; const excludes = [{ k: 'color', v: 'silver' },] console.log(excludeItems(items, excludes)); //Time Complexity: O(E + K * n) {where E: is excludes length, K: keys in the items, n: Total number of items } // space O(n) time 0(n * k) function excludeItemsBetter(items, excludes) { const map = new Map(); // O(n) for (let i = 0; i { for (const key in item) { const mapKey = `key:${key}-val:${item[key]}`; if (map.has(mapKey)) { return false; } } return true; }); } function excludeItemsBetter(items, excludes) { const map = new Map(); for (let i = 0; i { for (const key in item) { const mapKey = `key:${key}-val:${item[key]}`; if (map.has(mapKey)) { return false; } } return true; }); } Time complexity O(n*k) where k is the number of excludes. Nothing change if you change from: for(const item of items){ for(const exclude of excludes) { ... } } to for(const exclude of excludes){ for(const item of items) { ... } } time complexity will be the same. Main problems in this code I see next: 1. typo in the line ```item[pair.k] === item[pair.v]``` should be ```item[pair.k] === pair.v``` 2. overriding incoming parameter, it does not mutate the global items, but still it's bad practice in my opinion. 3. we can rewrite the code without using extra variables. my try: const excludeItems = (items, excludes) => items.filter(item => !excludes.some(({k,v}) => item[k] === v)) One or more comments have been removed. |
Front End Engineer at Facebook was asked...
Given a grid of characters output a decoded message. The message for the following would be IROCKA. (diagonally down right and diagonally up right if you can't go further .. you continue doing this) I B C A L K A D R F C A E A G H O E L A D 11 Answersas there are 21 characters and you describe a grid, I'm assuming it's 3x7: I B C A L K A D R F C A E A G H O E L A D Starting from the upper left and moving SE till a wall, then moving NE, then moving SE yields IROCLED, not IROCKA. However my human-powered fuzzy search is telling me it's much more likely that the answer is IROCKED, so I'm wondering whether the 1. author misremembered the original grid 2. the author misremembered the correct answer and the grid 3. I misunderstood the question. var arr=[['I','B','C','A','L','K','A'],['D','R','F','C','A','E','A'],['G','H','O','E','L','A','D']] var result=""; var goDownward; for(var j=0,i=0;j var arr=[['I','B','C','A','L','K','A'],['D','R','F','C','A','E','A'],['G','H','O','E','L','A','D']] var result=""; var goDownward; for(var j=0,i=0;j Show More Responses function decodeMessage(matrix) { let result = ''; let decode = function(matrix, i = 0, j = 0) { // check if matrix is null or empty if (matrix === null || matrix.length === 0) { return; } result += matrix[i][j]; //check the boundary of matrix with i and j let {x, y} = {x : matrix.length, y : matrix[0].length}; if ((i + 1) === x){ i -= 1; } else { i += 1; } j += 1; if (j === y) { return; } decode(matrix, i, j); } decode(matrix); return result; } let mat = [ ['I','B','C','A','L','K','A'], ['D','R','F','C','A','E','A'], ['G','H','O','E','L','A','D'] ]; console.log(decodeMessage(mat)); //IROCLED var arr = [ ['I','B','C','A','L','K','A'], ['D','R','F','C','A','E','A'], ['G','H','O','E','L','A','D'] ]; var row = 0, col = 0; var totalCols = arr[0].length; var totalRows = arr.length; var msg = ''; while (col < totalCols) { msg += arr[row][col]; // row++ if less than total rows // row-- if back at row 0 row = (row === 0 || row < totalRows - 1) ? row + 1 : row - 1; // always go forward in column col++; } // returns 'IROCLED' All solutions in here are wrong as they never go back up to the 0th row after first descent. ``` var arr = [ ['I','B','C','A','K','E','A'], ['D','R','F','C','A','E','A'], ['G','H','O','E','L','A','D'] ]; var row = 0, col = 0; var totalCols = arr[0].length; var totalRows = arr.length; var goingDown = false; var msg = ''; while (col < totalCols) { msg += arr[row][col]; // row++ if less than total rows // row-- if back at row 0 if (row === 0 || (row < totalRows - 1 && goingDown)) { row += 1; goingDown = true; } else { row -= 1; goingDown = false; } // always go forward in column col++; } console.log(msg) // IROCKED ``` var message = [ ['I', 'B', 'C', 'A', 'K', 'E', 'A'], ['D', 'R', 'F', 'C', 'A', 'E', 'A'], ['G', 'H', 'O', 'E', 'L', 'A', 'D'] ]; let forward = false, col = 0; for (let row = 0, len = message[0].length; row var message = [ ['I', 'B', 'C', 'A', 'K', 'E', 'A'], ['D', 'R', 'F', 'C', 'A', 'E', 'A'], ['G', 'H', 'O', 'E', 'L', 'A', 'D'] ]; let forward = false, col = 0; for (let row = 0, len = message[0].length; row < len; row++) { console.log(message[col][row]); // I R O C K E D if (col === 0 || col === 2) forward = !forward; forward ? col++ : col--; } function decode (matrix = []) { let i = 1 const sizeY = matrix.length - 1 const recurse = function (message, x, y) { if (y sizeY) { i = y = row.length) { return message } return recurse( message + row[x], x + 1, y + i, ) } return recurse('', 0, 0) } decode([ ['I', 'B', 'C', 'A', 'K', 'E', 'A'], ['D', 'R', 'F', 'C', 'A', 'E', 'A'], ['G', 'H', 'O', 'E', 'L', 'A', 'D'] ]) // IROCKED function getWord(met) { let arr = []; let i = met.length - 1; let j = met[0].length - 1; let a = 0; let direction = 1; for(let b = 0; b = i) { direction = -1; } else if(a === 0) { direction = 1; } a = a + direction; } return arr; } let sample= [ ['I', 'B', 'C', 'A', 'L', 'K', 'A'], ['D', 'R', 'F', 'C', 'A', 'E', 'A'], ['G', 'H', 'O', 'E', 'L', 'A', 'D'] ]; getWord(sample); const grid = [ ["I", "B", "C", "A", "L", "K", "A"], ["D", "R", "F", "C", "A", "E", "A"], ["G", "H", "O", "E", "L", "A", "D"] ]; const decoder = (grid)=>{ const rowsLen = grid.length; let isDown = true; const result = []; let column = 0; let row = 0; while(column < grid[0].length){ result.push(grid[row][column]); column++; if(isDown){ if(row+1 === rowsLen){ isDown = false; row--; }else{ row++; } }else{ if(row-1 <0){ isDown = true; row++; }else{ row--; } } } return result; } console.log(decoder(grid)) |
See Interview Questions for Similar Jobs
- Web Developer
- Front End Developer
- Software Engineer
- Software Developer
- Front End Engineer
- Senior Software Engineer
- Web Designer
- Senior Web Developer
- Junior Web Developer
- Senior Front End Developer
- UI Developer
- Software Development Engineer
- Front End Software Engineer
- Front End
- Junior Front End Developer
- Developer
- Business Analyst