I'm trying to add elements as asterisks inside array based on number of elements. Basically If numberOfRows is 3 then I want this output:
[
' * ',
' *** ',
'*****'
]
I'm struggling on setting asterisks using the index. Can anyone point me in the right direction? Thanks a lot!
Here's my code:
function myFunction(numberOfRows) {
var arr = [];
var value = "";
var asterisk = "*"; // Need to update this based on number of rows
for (var i = 1; i <= numberOfRows; i++) {
value += asterisk;
arr.push(value);
}
return arr;
}
Got it working! Here's a perfect solution.
function myFunction(n) {
let arr = [];
for(let f = 1; f <= n; f++) {
arr.push(' '.repeat(n - f) + '*'.repeat(f + f - 1) + ' '.repeat(n - f));
}
return arr;
}
console.log(myFunction(3));
Try something like this;
function myFunction(numberOfRows) {
var arr = [];
var value = "";
var slots = numberOfRows * 2 - 1;
var spaceSlots, asteriskSlots, spaces;
for (var i = 0; i < numberOfRows; i++) {
asteriskSlots = i * 2 + 1;
spaceSlots = Math.floor((slots - asteriskSlots)/2);
spaces = new Array(spaceSlots).fill(' ').join('');
value = spaces + '*'.repeat(asteriskSlots) + spaces;
arr.push(value);
}
return arr;
}
console.log(myFunction(20));
I have written a Javascript file of two algorithms. As shown in the code below, I am using a for loop to generate random values which are used by both algorithms as input.
At present, I am displaying output of the binarySearch and SearchSorted alternatively.
The problem I am facing is I have to pass the same array values generated by randomlyGenerateArray in the main program to both the algorithms for a meaningful comparison. But I don't know how to change the output format.
I have thought of adding them in different loops, but as I have explained above i need to use the same randomArray values for both the algorithms.
i.e., The below code produces output as shown below -
Binary Search Successful 1
Search Sorted Successful 5
Binary Search Successful 3
Search Sorted Successful 10
How do I display the output of Binary Search First and then display output of Search Sorted? it's something like this. Any help will be greatly appreciated.
Binary Search Successful 1
Binary Search Successful 3
Search Sorted Successful 5
Search Sorted Successful 10
// Binary Search Algorithm
function binarySearch(A,K)
{
var l = 0; // min
var r = A.length - 1; //max
var n = A.length;
var operations = 0;
while(l <= r)
{
var m = Math.floor((l + r)/2);
operations++;
if(K == A[m])
{
console.log('Binary Search Successful %d',operations);
return m;
}
else if(K < A[m])
{
r = m - 1;
}
else
{
l = m + 1;
}
}
operations++;
console.log('Binary Search Unsuccessful %d',operations);
return -1;
}
// Search Sorted Algorithm
function searchSorted(A, K)
{
var n = A.length;
var i = 0;
var operations = 0;
while (i < n)
{
operations++;
if (K < A[i])
{
return -1;
}
else if (K == A[i])
{
console.log('Search Sorted Successful %d', operations);
return i;
}
else
{
i = i + 1;
}
}
operations++;
console.log('Search Sorted Unsuccessful %d', operations);
return -1;
}
// Random Array generator
var randomlyGenerateArray = function(size)
{
var array = [];
for (var i = 0; i < size; i++)
{
var temp = Math.floor(Math.random() * maxArrayValue);
var final = array.splice(5, 0, 30);
array.push(final);
}
return array;
}
//Sort the Array
var sortNumber = function(a, b)
{
return a - b;
}
// Main Program
var program = function()
{
var incrementSize = largestArray / numberOfArrays;
for (var i = smallestArray; i <= largestArray; i += incrementSize)
{
var randomArray = randomlyGenerateArray(i);
var sort = randomArray.sort(sortNumber);
var randomKey = 30;
binarySearch(sort, randomKey);
searchSorted(sort, randomKey);
}
}
var smallestArray = 10;
var largestArray = 10000;
var numberOfArrays = 1000;
var minArrayValue = 1;
var maxArrayValue = 1000;
program();
You could store the sorted randomArrays in an array (which I've called sortedRandomArrays), then run a for loop for each search.
The Main Program would then look like:
// Main Program
var program = function()
{
var incrementSize = largestArray / numberOfArrays;
var sortedRandomArrays = [];
for (var i = smallestArray; i <= largestArray; i += incrementSize)
{
var randomArray = randomlyGenerateArray(i));
var sort = randomArray.sort(sortNumber);
sortedRandomArrays.push(sort);
var randomKey = 30;
}
for (var i = 0; i < sortedRandomArrays.length; i++)
{
binarySearch(sortedRandomArrays[i], randomKey);
}
for (var i = 0; i < sortedRandomArrays.length; i++)
{
searchSorted(sortedRandomArrays[i], randomKey);
}
}
Solution is simple: store the results and print with 2 separate loops (take out the printing from within the functions).
var program = function()
{
var binarySearchResults = [];
var sortedSearchResults = [];
var incrementSize = largestArray / numberOfArrays;
for (var i = smallestArray; i <= largestArray; i += incrementSize)
{
var randomArray = randomlyGenerateArray(i);
var sort = randomArray.sort(sortNumber);
var randomKey = 30;
binarySearchResults[i] = binarySearch(sort, randomKey);
sortedSearchResults[i] = searchSorted(sort, randomKey);
}
for (var i = smallestArray; i <= largestArray; i += incrementSize)
{
//print binary results
}
for (var i = smallestArray; i <= largestArray; i += incrementSize)
{
//print sorted results
}
}
I must be doing something stupid. The array newArea needs to add up data from all regions, i.e. be global. Regions are represented by variable p. But when I try to get newArea array to add to itself, e.g. newArea[p] += otherArray, it outputs NaNs. Even newArea[p] += 1 outputs NaNs.
Can anyone spot what I'm doing wrong? It's driving me mad and I'm working to a deadline.
mm=0
var maxVolume = 0;
var tempCAGR = 0;
var maxCAGR = 0;
var newArray = [];
var newRegions = [];
var newConsValues = [];
var newArea = [];
for (var p=0; p<arrayRef[mm].length; p++) {//9 regions
newArray[p] = [];
for (var q=0; q<arrayRef[mm][p].length; q++) {//4 scenarios
newArea[q] = [];
if (q==0) {
newRegions.push(arrayRef[mm][p][q][0]);
newConsValues.push(arrayRef[mm][p][q][1]);
}
for (var r=0; r<dates.length; r++) {//time
//console.log('p: '+p+', q: '+q+', r: '+r);
if (p==0) {
newArea[q][r] = 1;
} else {
newArea[q][r] += 1;
}
}
arrayRef[mm][p][q].shift();
tempCAGR = Math.pow(( arrayRef[mm][p][q][len] / arrayRef[mm][p][q][1] ),(1/len))-1;
//console.log(newRegions[p]+', num: '+arrayRef[mm][p][q][len-1]+', denom: '+arrayRef[mm][p][q][0]+', len: '+len+', cagr: '+tempCAGR);
newArray[p][q] = tempCAGR;
maxCAGR = Math.max(maxCAGR,tempCAGR);
}
}
console.log(newArea);
You are cleaning the array in newArea everytime you loop through it:
...loop q ...
newArea[q] = []; // <-- resets the array at q pos
... loop r ...
if (p==0) {
newArea[q][r] = 1;
} else {
newArea[q][r] += 1;
}
So when p === 0 it will fill an array at q pos of your newArea array. However, next iteration of p will clear them out, so there's nothing there to sum.
You probably want to keep the old array or create a new one if there isn't one.
newArea[q] = newArea[q] || [];
It looks like you do not have the variable initialised. With adding something to undefined, you get NaN.
You can change the art of incrementing with a default value:
if (p == 0) {
newArea[q][r] = 1;
} else {
newArea[q][r] = (newArea[q][r] || 0) + 1;
}
I have quite complicated array which I need to transform to specific format. The array looks like this:
arr = [["name1",51,1,"code1",3],["name2",52,0,"code2",4,"code3",6],["name3",51,2,"code4",3,"code5",6,"code6",1],["name4",55,5,"code7",7,"code8",1],["name5",54,2,"code9",5,"code10",8]];
Each array in my output need contains only 5 values - 3 first values always will be the same like in input. The next 2 values should contain code and the lowest value from the rest of the array. So this case output will look like this:
output = [["name1",51,1,"code1",3],["name2",52,0,"code2",4],["name3",51,2,"code6",1],["name4",55,5,"code8",1],["name5",54,2,"code9",5]];
For start I think the best is use loop for and if instruction, but I don't know how to cope with this later on.
for (i=0; i<arr.length; i++) {
if (arr[i]>5) {
//dont know what to put here
}
}
My solution:
arr = [
["name1",51,1,"code1",3],
["name2",52,0,"code2",4,"code3",6],
["name3",51,2,"code4",3,"code5",6,"code6",1],
["name4",55,5,"code7",7,"code8",1],
["name5",54,2,"code9",5,"code10",8]
];
function process_array(in_array) {
var output = [];
/* check each element in array */
in_array.forEach(function(sub_array){
/* store new sub array here*/
var last_sub_out = [];
var code;
var lowest_num = Number.MAX_VALUE;
/* check sub array
#value is value of sub_array
#index is index of that value.
*/
sub_array.forEach(function(value, index){
/* add first 3 values */
if(index < 3) {
last_sub_out.push( value );
return;
}
/* checking only numbers(even index: 4,6,8, ...) */
if(index % 2 == 0) {
if(value < lowest_num) {
code = sub_array[index - 1];
lowest_num = value;
}
}
});
/* add found code with lowest number */
last_sub_out.push(code, lowest_num);
output.push( last_sub_out );
/* LOG */
document.write(last_sub_out.join(', ') + "</br>");
});
return output;
}
var out = process_array(arr);
var arr = [["name1",51,1,"code1",3],["name2",52,0,"code2",4,"code3",6],["name3",51,2,"code4",3,"code5",6,"code6",1],["name4",55,5,"code7",7,"code8",1],["name5",54,2,"code9",5,"code10",8]];
var out=[];
for (i=0; i < arr.length; i++) {
if (arr[i].length>5) {
out[i] = [arr[i][0], arr[i][1], arr[i][2]];
c = [arr[i][3], arr[i][4]];
for (j=0; j < (arr[i].length - 5)/2; j++){
if (c[1] > arr[i][6+2*j]){
c = [arr[i][5+2*j], arr[i][6+2*j]];
}
}
out[i][3] = c[0]; out[i][4] = c[1];
} else {
out[i] = arr[i]
}
}
Try:
var arr = [["name1",51,1,"code1",3],["name2",52,0,"code2",4,"code3",6],["name3",51,2,"code4",3,"code5",6,"code6",1],["name4",55,5,"code7",7,"code8",1],["name5",54,2,"code9",5,"code10",8]];
var output = [], startIndex = 3, i = 0;
while(i < arr.length){
var item = arr[i++], j = startIndex, count = 0, min = Infinity, code;
while(j < item.length){
count++ % 2 && item[j] < min && (min = item[j], code = item[j-1]);
j++
}
item.splice(startIndex, item.length, code, min);
output.push(item)
}
document.write("<pre>" + JSON.stringify(output, null, 4) + "<pre>");
In Javascript, I have a matrix with a variable number of rows and columns, which I wish to store in a multi-dimensional array.
The problem is that I need extra 3 columns and 3 extra rows with negative indexes in the matrix too. So the result for a 10x10 matrix should be a 13x13 array with indexes from -3 to 9.
I define the array with:
var numberofcolumns = 10;
var numberofrows = 10;
var matrix = [];
for (var x = -3; x < numberofcolumns; x++) {
matrix[x] = [];
}
Is this the right way to do this? Or is there a better way?
While you can create attributes that are negative numbers, you lose some of Javascript's pseudo-array magic. In particular, matrix.length will still be 10 even though it has 13 elements. And the code in general may be surprising to anyone reading it.
You might be better off defining an offset to get the value you need out of the array index and vice-versa:
var offset = 3
for (var x=-3; x<numberofcolumns; x++) {
matrix[x+offset] = []
}
You could define the matrix as an object instead. You would lose some array functionality but you could still access matrix[-3] for example.
var numberofcolumns = 10;
var numberofrows = 10;
var matrix = {};
for (var x = -3; x < numberofcolumns; x++) {
matrix[x] = [];
}
for (x in matrix) {
console.log(matrix[x]);
}
Or you could define your own class starting as an object or array and work from there. Here's something to get you started:
function Matrix() { };
Matrix.prototype.LBound = function()
{
var n;
for (i in this) {
if (!isNaN(i) && (isNaN(n) || n > i))
n = parseInt(i);
}
return n;
};
Matrix.prototype.UBound = function()
{
var n;
for (i in this) {
if (!isNaN(i) && (isNaN(n) || n < i))
n = parseInt(i);
}
return n;
};
Matrix.prototype.length = function()
{
var length = this.UBound() - this.LBound();
return isNaN(length) ? 0 : length+1;
};
Matrix.prototype.forEach = function(callback, indexes)
{
if (!indexes) var indexes = [];
for (var i = this.LBound(); i <= this.UBound() ; i++)
{
indexes[Math.max(indexes.length-1, 0)] = i;
callback(this[i], indexes);
if (this[i] instanceof Matrix)
{
var subIndexes = indexes.slice();
subIndexes.push("");
this[i].forEach(callback, subIndexes);
}
}
};
Matrix.prototype.val = function(newVal)
{
if (newVal)
{
this.value = newVal;
return this;
}
else
{
return this.value;
}
};
Then you'd create your matrix as such
var numberofcolumns = 10;
var numberofrows = 10;
var matrix = new Matrix();
for (var i = -3; i < numberofcolumns; i++) {
matrix[i] = new Matrix();
for (var j = -4; j < numberofrows; j++) {
matrix[i][j] = new Matrix();
matrix[i][j].val("test " + i + " " + j);
}
}
And you can run some cool functions on it
console.log("Upper bound: " + matrix.LBound());
console.log("Lower bound: " + matrix.UBound());
console.log("Length: " + matrix.length());
matrix.forEach(function(item, index)
{
if (item.val())
console.log("Item " + index + " has the value \"" + item.val() + "\"");
else
console.log("Item " + index + " contains " + item.length() + " items");
});
DEMO: http://jsfiddle.net/uTVUP/
I agree with Mark Reed's points about this being a unintuitive use of Array. I think a subclass is in order. You could follow the tutorial here to subclass Array, keep the native bracket notation, and override methods like length() so they give sensible values. Subclassing would have the added advantage of making it clear to those reading your code that something besides your everyday array is going on.