I experience a strange differences in performance of simple task depending of array I am working with. The task is to calculate sum of those elements in array which are greater than 5. Task is performed on arrays with equal lenghts.
I try the very same approach on three different array objects:
1) var hugeArray1 - array with all elemenets randomly picked from 0:10 range
2) var hugeArray2 - copy of hugeArray1 sorted with Array.prototype.sort()
3) var hugeArray3 - handcrafted but sorted array with values from 0:10 range, spread to equaly cover this interval.
I try to calculate sum of elements greater than 5 many times for each Array and then average them. What is strange, time needed varies a lot for those three arrays.
1) hugeArray1: 5.805ms
2) hugeArray2: 15.738ms
3) hugeArray3: 3.753ms
Result for array sorted with sort() is extreamly poor. Why is that? it looks like sort() returns some kind of wraper/proxy instead of 'native' Array, which affects performance. I tried it on 2 computers. Also i tried to change order of testing.
I include code below, please tell me what is happening here.
// random array with elements 0-10 of size n
function randomArray(n) {
var arr = [];
for (var i = 0; i < n; ++i) {
arr.push(Math.random() * 10);
}
return arr;
};
// measures time of execution
function measureTime(f) {
var start = new Date().getTime();
f();
var stop = new Date().getTime();
return stop - start;
};
// enumerate ofer array and calculate sum of elementsgreater than 5
function sumGreaterThan5(arr) {
var sum = 0;
for (var i = 0; i < arr.length; ++i) {
if (arr[i] > 5.0)
sum += arr[i];
}
return sum;
}
// generate array os size 'size' with elements with constant step to fill interval 0:10
function generateSortedArr(size) {
var arr = [];
for (var i = 0; i < size; ++i) {
arr.push(i * 10 / size);
}
return arr;
}
var huge = 1000000;
var hugeArray1 = randomArray(huge);
var hugeArray2 = hugeArray1.slice(0).sort();
var hugeArray3 = generateSortedArr(huge);
var hugeArrays = [hugeArray1, hugeArray2, hugeArray3];
hugeArrays.forEach(x=> {
var res = [];
for (var i = 0; i < 1000; ++i) {
res.push(measureTime(function () {
sumGreaterThan5(x);
}));
}
console.log(res.reduce((prev, curr)=> prev + curr) / res.length);
});
// random array with elements 0-10 of size n
function randomArray(n) {
var arr = [];
for (var i = 0; i < n; ++i) {
arr.push(Math.random() * 10);
}
return arr;
};
// measures time of execution
function measureTime(f) {
var start = new Date().getTime();
f();
var stop = new Date().getTime();
return stop - start;
};
// enumerate ofer array and calculate sum of elementsgreater than 5
function sumGreaterThan5(arr) {
var sum = 0;
for (var i = 0; i < arr.length; ++i) {
if (arr[i] > 5.0)
sum += arr[i];
}
return sum;
}
// generate array os size 'size' with elements with constant step to fill interval 0:10
function generateSortedArr(size) {
var arr = [];
for (var i = 0; i < size; ++i) {
arr.push(i * 10 / size);
}
return arr;
}
var huge = 1000000;
var hugeArray1 = randomArray(huge);
var hugeArray2 = hugeArray1.slice(0).sort();
var hugeArray3 = generateSortedArr(huge);
var hugeArrays = [hugeArray1, hugeArray2, hugeArray3];
hugeArrays.forEach(function(x){
var res = [];
for (var i = 0; i < 1000; ++i) {
res.push(measureTime(function () {
sumGreaterThan5(x);
}));
}
console.log(res.reduce(function(prev, curr){return prev + curr},0) / res.length);
});
Related
I'm asking for help to find the sum of an array with elements that were pushed from a counter variable that had previously looped 10 times. I'm new to Javascript and was practicing for an assessment, and I've tried several different ways to do it and have only resulted with just a list of the elements within the numbers array.
var counter = 10;
var numbers = [];
for (i = 1; i <= 10; i ++) {
counter = [i + 73];
numbers.push(counter);
}
console.log(numbers);
function sum(arr) {
var s = 0;
for(var i = 0; i < arr.length; i++) {
s = s += arr[i];
}
return s;
}
console.log(sum([numbers]));
function getArraySum(a) {
var total = 0;
for (var i in a) {
total += a[i];
}
return total;
}
var numbers = getArraySum([numbers]);
console.log(numbers);
you should push only the value of counter without the brackets and then make a reduce to have the sum of each number in the array
var counter = 10;
var numbers = [];
for (i = 1; i <= 10; i++) {
counter = i + 73;
numbers.push(counter);
}
console.log(numbers.reduce((a,b) => a+b));
You had a couple of typos in the code:
Typos
You were wrapping the sum in square brackets:
counter = [i + 73];
You should just remove the brackets like:
counter = i + 73;
2. You were wrapping a value that is already an array in square brackets while passing it as an argument to a function:
sum( [numbers] )
// ...
getArraySum( [numbers] );
You should remove the brackets, like this:
sum( numbers );
// ...
getArraySum( numbers );
Fix
I updated the code that you shared to fix the above-mentioned things:
var numbers = [];
// Loop 10 times and push each number to the numbers array
for (var i = 1; i <= 10; i ++) {
var sumNumbers = i + 73;
numbers.push(sumNumbers);
}
console.log(numbers);
function sum(arr) {
var total = 0;
for(var i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
// Call the function by passing it the variable numbers, holding an array
var result1 = sum(numbers);
console.log( result1 );
function getArraySum(a) {
var total = 0;
for (var i in a) {
total += a[i];
}
return total;
}
var result2 = getArraySum(numbers);
console.log(result2);
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 am attempting to write a single function in javascript that compares credit card numbers listed strings within an array. The function should find the credit card number with the largest sum, and return that number as the original string within the input array. I am completely stuck, and cannot get past this 'undefined' error message. Here is what I have:
function highest(inputArray) {
var sum = 0;
var currentHighest = 0;
var largest = 0;
for (a = 0; a < inputArray.length; a++) {
var tempArray = inputArray[a].replace(/\D/g, '');
}
function sumDigits(str) {
sum = 0;
for (i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i), 16);
}
return sum;
}
if (sumDigits(tempArray) >= currentHighest) {
currentHighest = sum;
largest = inputArray[a];
return largest;
} else {
return largest;
}
}
var numberArray = [];
console.log(highest(numberArray));
You have a good number of basic errors in your code. Rather than break it down, I will simply put the code revision in here.
var ipa = ['4916-2600-1804-0530', '4779-2528-0088-3972', '4252-2788-0093-7978', '4556-4242-9283-2260'];
function highest(inputArray) {
var currentHighest = 0;
var largest = 0;
var tempArray = [];
for (var a = 0; a < inputArray.length; a++) {
tempArray.push(inputArray[a].replace(/\D/g, ''));
}
function sumDigits(strA) {
var sum = 0;
for (var i = 0; i < strA.length; i++) {
sum += parseInt(strA.charAt(i), 10);
}
return sum;
}
for (var a = 0; a < tempArray.length; a++) {
var csum = sumDigits(tempArray[a]);
if (csum >= currentHighest) {
currentHighest = csum;
largest = inputArray[a];
}
}
return largest;
}
console.log(highest(ipa));
'use strict';
// initial array of numbers
let numbers = ['4916-2600-1804-0530', '4779-2528-0088-3972', '4252-2788-0093-7978', '4556-4242-9283-2260'];
// remove "-" symbol
let normilized = numbers.map(number => number.replace(/-/g, ''));
// get sum for each number
let sums = normilized.map(
number => [].reduce.call(number, (prev, value) => {
prev += +value;
return prev;
}, 0));
// find max sum
let max = Math.max.apply(null, sums);
// find position of that sum
let indexOfMax = sums.indexOf(max);
// get card number
console.log(numbers[indexOfMax]);
Based on my understanding of your question, I hope this is what you are looking for.
In addition to doing a basic loop over the array, you can also sort the array in ascending order and simply pick out the last item of the array for your largest credit card number.
Sample Fiddle here:
https://jsfiddle.net/xxo3m8zf/1/
Sample Function:
function largestSum(arr) {
arr.sort();
return largest = arr[arr.length-1];
}
I have a numeric 2D array (an array of arrays, or a matrix) and I need to do simple matrix operations like adding a value to each row, or multiplying every value by a single number. I have little experience with math operations in JavaScript, so this may be a bone-headed code snippet. It is also very slow, and I need to use it when the number of columns is 10,000 - 30,000. By very slow I mean roughly 500 ms to process a row of 2,000 values. Bummer.
var ran2Darray = function(row, col){
var res = [];
for (var i = 0 ; i < row; i++) {
res[i] = [];
for (var j = 0; j < col; j++) {
res[i][j] = Math.random();
}
}
return res;
}
var myArray = ran2Darray(5, 100);
var offset = 2;
for (i = 0; i < myArray.length; i++) {
aRow = myArray[i];
st = Date.now();
aRow.map(function addNumber(offset) {myArray[i] + offset*i; })
end = Date.now();
document.write(end - st);
document.write("</br>");
myArray[i] = aRow;
}
I want to avoid any added libraries or frameworks, unless of course, that is my only option. Can this code be made faster, or is there another direction I can go, like passing the calculation to another language? I'm just not familiar with how people deal with this sort of problem. forEach performs roughly the same, by the way.
You don't have to rewrite array items several times. .map() returns a new array, so just assign it to the current index:
var myArray = ran2Darray(5, 100000);
var offset = 2;
var performOperation = function(value, idx) {
return value += offset * idx;
}
for (i = 0; i < myArray.length; i++) {
console.time(i);
myArray[i] = myArray[i].map(performOperation)
console.timeEnd(i);
}
It takes like ~20ms to process.
Fiddle demo (open console)
Ok, Just a little modification and a bug fix in what you have presented here.
function addNumber(offset) {myArray[i] + offset*i; }) is not good.
myArray[i] is the first dimention of a 2D array why to add something to it?
function ran2Darray (row, col) {
var res = [];
for (var i = 0 ; i < row; i++) {
res[i] = [];
for (var j = 0; j < col; j++) {
res[i][j] = Math.random();
}
}
return res;
}
var oneMillion = 1000000;
var myArray = ran2Darray(10, oneMillion);
var offset = 2;
var startTime, endTime;
for (i = 0; i < myArray.length; i++) {
startTime = Date.now();
myArray[i] = myArray[i].map(function (offset) {
return (offset + i) * offset;
});
endTime = Date.now();
document.write(endTime - startTime);
document.write("</br>");
}
try it. It's really fast
https://jsfiddle.net/itaymer/8ttvzyx7/
I have a very big array which looks similar to this
var counts = ["gfdg 34243","jhfj 543554",....] //55268 elements long
this is my current loop
var replace = "";
var scored = 0;
var qgram = "";
var score1 = 0;
var len = counts.length;
function score(pplaintext1) {
qgram = pplaintext1;
for (var x = 0; x < qgram.length; x++) {
for (var a = 0, len = counts.length; a < len; a++) {
if (qgram.substring(x, x + 4) === counts[a].substring(0, 4)) {
replace = parseInt(counts[a].replace(/[^1-9]/g, ""));
scored += Math.log(replace / len) * Math.LOG10E;
} else {
scored += Math.log(1 / len) * Math.LOG10E;
}
}
}
score1 = scored;
scored = 0;
} //need to call the function 1000 times roughly
I have to loop through this array several times and my code is running slowly. My question is what the fastest way to loop through this array would be so I can save as much time as possible.
Your counts array appears to be a list of unique strings and values associated with them. Use an object instead, keyed on the unique strings, e.g.:
var counts = { gfdg: 34243, jhfj: 543554, ... };
This will massively improve the performance by removing the need for the O(n) inner loop by replacing it with an O(1) object key lookup.
Also, avoid divisions - log(1 / n) = -log(n) - and move loop invariants outside the loops. Your log(1/len) * Math.LOG10E is actually a constant added in every pass, except that in the first if branch you also need to factor in Math.log(replace), which in log math means adding it.
p.s. avoid using the outer scoped state variables for the score, too! I think the below replicates your scoring algorithm correctly:
var len = Object.keys(counts).length;
function score(text) {
var result = 0;
var factor = -Math.log(len) * Math.LOG10E;
for (var x = 0, n = text.length - 4; x < n; ++x) {
var qgram = text.substring(x, x + 4);
var replace = counts[qgram];
if (replace) {
result += Math.log(replace) + factor;
} else {
result += len * factor; // once for each ngram
}
}
return result;
}