In: Computer Science
Challenge 1 – 2D Array Maker
Create a function that takes in two parameters and returns a
created two-dimension array.
var twoD = Make2D(<width>, <height>);
Challenge 2 – Fill 2D Array
Create a function that takes a single parameter and fills the 2D
array with that parameter
Use Cases:
Fill2D(<twoD array>, <fill value>); //fills twoD
twoD = fill2D(<twoD array>, <fill value>); //fills
twoD, but also returns reference
Challenge 3 – Make 2D Array
Write a function that takes 3 parameters and makes use of your
prior two functions to create a 2D array filled with a default
parameter.
var twoD = Init2D(<width>, <height>, <fill
val>);
Coded in Java script
Solution:
Challenge 1 – 2D Array Maker
Create a function that takes in two parameters and returns a
created two-dimension array.
var twoD = Make2D(<width>, <height>);
Code for function:
function Make2D(width,height)
{
twoD= new Array(height);
for(var i=0;i < height ;i++)
{
twoD[i] = new Array(width);
}
return twoD;
}
Challenge 2 – Fill 2D Array
Create a function that takes a single parameter and fills the 2D
array with that parameter
Use Cases:
Fill2D(<twoD array>, <fill value>); //fills twoD
twoD = fill2D(<twoD array>, <fill value>); //fills
twoD, but also returns reference
Code for function:
function fill2D(twoD,value)
{
for (var i = 0; i < twoD.length; i++)
{
for (var j = 0; j < twoD[i].length; j++)
{
twoD[i][j] = value;
}
}
return twoD;
}
Challenge 3 – Make 2D Array
Write a function that takes 3 parameters and makes use of your
prior two functions to create a 2D array filled with a default
parameter.
var twoD = Init2D(<width>, <height>, <fill
val>);
Code for function:
function Init2D(width, height, value)
{
twoD=Make2D(width,height);
twoD=fill2D(twoD,value);
return twoD;
}
Complete code of all functions with implementation:
function Make2D(width,height)
{
twoD= new Array(height);
for(var i=0;i < height ;i++)
{
twoD[i] = new Array(width);
}
return twoD;
}
function fill2D(twoD,value)
{
for (var i = 0; i < twoD.length; i++)
{
for (var j = 0; j < twoD[i].length; j++)
{
twoD[i][j] = value;
}
}
return twoD;
}
function Init2D(width, height, value)
{
twoD=Make2D(width,height);
twoD=fill2D(twoD,value);
return twoD;
}
var twoD = Make2D(3,4);
console.log(twoD);
twoD = fill2D(twoD, 2);
console.log(twoD);
twoD = Init2D(5, 6, 7);
console.log(twoD);
Screenshot of complete code and output: