I wanted to check to see which was faster in adding elements to an array in javascript:
Adding a list of 5 per iteration
Adding 5 single items with adding position to the subscript
Adding one single item pr iteration
I ran it on my Linux Mint 16, Firefox 37.0.2
1 and 2 turned out much better than 3.
When I ran it 1,000,000 times 1 was noticably better than 2.
However when I ran it 10,000,000 the results were reversed. What would be the explanation for that?
var amount = 1000000;
var iter = 11;
var a = new Array(amount);
var b = new Array(amount);
var results = [];
for (j=1; j<iter; j++) {
var clock = new Date().getTime();
for (i=0; i< amount; i+=5) {
a[i] = [2,2,2,2,2];
}
results.push("quintuple primitive insert attempt " + j + " took " +
eval(new Date().getTime() - clock) + "ms");
var clock = new Date().getTime();
for (i=0; i< amount; i+=5) {
a[i] = 2;
a[i+1] = 2;
a[i+2] = 2;
a[i+3] = 2;
a[i+4] = 2;
}
results.push("single primitive insert with inline inc attempt " + j +
" took " + eval(new Date().getTime() - clock) + "ms");
var clock = new Date().getTime();
for (i=0; i< amount; i++) {
a[i] = 2;
}
results.push("single primitive insert with single iterator attempt " +
j + " took " + eval(new Date().getTime() - clock) + "ms");
}
The code is demonstrated here:
http://jsfiddle.net/lash/cL3wewj4/
(I also tried using homogenous and heterogenous arrays to insert content, in which 2 always was the best. The attempt is in the same jsfiddle source, commented out)
You're taking times of things that are not the same:
First off, you're taking times of creating a matrix whose elements at position i%5 = 0 contain an array of five elements. The rest of the elements (i%5 != 0) are undefined. This array has a length that depends on amount due to the fact that you're adding to the variable i five in each iteration and some elements at the end of the array might not be initialized (directly or indirectly).
for (i = 0; i < amount; i += 5) {
a[i] = [2, 2, 2, 2, 2];
}
Secondly, you're creating an array whose elements are all equal to 2.
for (i = 0; i < amount; i += 5) {
a[i] = 2;
a[i + 1] = 2;
a[i + 2] = 2;
a[i + 3] = 2;
a[i + 4] = 2;
}
Thirdly, you're doing the same as two.
for (i=0; i< amount; i++) {
a[i] = 2;
}
Since one is different than 2 and 3 the results don't make sense.
Related
So I've already found posts on this topic, but that didn't really help me. On the one hand, I have tried something like this, for example, but it is not quite right in my case**(C#)**.
string temp;
foreach (var a in chaine)
temp = ( Convert.ToUInt16(a).ToString("X4"));
for (j = 0; j < intlenght; j+= 1)
{
arrayData[j + 1] = temp;
}
Why I think it doesn't really work is that my starting form looked a little different than the examples and I'm not really familiar with JavaScript. My starting shape looks like this**(javaScript)**:
for (j = 0; j < intlenght; j+= 1)
{
arrayData[j + 1] = x.charCodeAt(j) - 32;
}
the x in this case it is actually
var x = document.getElementById ("textIn"). value;
but in my method I have a string return value instead of the X
so how can i correctly get the
arrayData [j + 1] = x.charCodeAt (j) - 32;
translate in c #. In the end I need this in my method for Code128 encoder
EDIT for better Understanding:
So I have a TextBlock in my window, but there is a text in it in a barcode 128 font. However, this barcode cannot yet be read. So what I want to do is add the additional characters of the barcode so that at the end you can scan this barcode with a scanning program. To do that I come across this Stack Overflow answer: https://stackoverflow.com/a/60363928/17667316
However, the problem was with the question that the code is in JavaScript and not in C #. Since I've only found solutions where it works with libaries and nuggets (which I want to work around) I tried to convert this javaScript code into C #. I come across lines like this(javaScript):
arrayData[j + 1] = x.charCodeAt(j) - 32;
I didn't find a solution to this as I did this Javascript code:
var buttonGen = document.getElementById("btnGen");
buttonGen.onclick = function () {
var x = document.getElementById("textIn").value;
var i, j, intWeight, intLength, intWtProd = 0, arrayData = [], fs;
var arraySubst = [ "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê" ];
/*
* Checksum Calculation for Code 128 B
*/
intLength = x.length;
arrayData[0] = 104; // Assume Code 128B, Will revise to support A, C and switching.
intWtProd = 104;
for (j = 0; j < intLength; j += 1) {
arrayData[j + 1] = x.charCodeAt(j) - 32; // Have to convert to Code 128 encoding
intWeight = j + 1; // to generate the checksum
intWtProd += intWeight * arrayData[j + 1]; // Just a weighted sum
}
arrayData[j + 1] = intWtProd % 103; // Modulo 103 on weighted sum
arrayData[j + 2] = 106; // Code 128 Stop character
chr = parseInt(arrayData[j + 1], 10); // Gotta convert from character to a number
if (chr > 94) {
chrString = arraySubst[chr - 95];
} else {
chrString = String.fromCharCode(chr + 32);
}
// Change the font-size style to match the drop down
fs = document.getElementsByTagName("option")[document.getElementById("selList").selectedIndex].value;
document.getElementById("test").style.fontSize = fs + 'px';
document.getElementById("check").innerHTML =
'Checksum = ' + chr + ' or character ' + // Make It Visual
chrString + ', for text = "' + x + '"';
document.getElementById("test").innerHTML =
'Ì' + // Start Code B
x + // The originally typed string
chrString + // The generated checksum
'Î'; // Stop Code
}
Can convert into a working C # code.
How to write a JavaScript program to randomly generate a single digit number (0,1,…9) one hundred times and output how many 0s,1s, 2s,….9s were generated.
I can generate a hundred numbers (see below) but can't figure out how to sort them into counters
<script>
for (i = 0; i < 100; i++) {
num = Math.floor((Math.random() * 10));
document.write(num);
}
</script>
You can save the number of each number in an array where each index represents its corresponding number (i.e. the 0th index will contain the number of 0s generated) and then increment the number in the array each time it comes up from the Math.random.
var numOfEachNumber = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (var i = 0; i < 100; i++) {
var num = Math.floor((Math.random() * 10));
numOfEachNumber[num]++; // Increment the value of the index of the number
// that was generated
document.write(num);
}
for (var i = 0; i < 10; i++) {
document.write(i + ': ' + numOfEachNumber[i]);
}
You could count frequencies with a counter-object.
var counter = {};
for (i = 0; i <= 100; i += 1)
{
num = Math.floor((Math.random() * 10));
counter[num] = (counter[num]) ? (counter[num]) += 1 : counter[num] = 1;
}
print = function(x) { console.log(x + ": " + counter[x]); };
Object.keys(counter).forEach(print);
And here is the Fiddle to play with.
I'm pretty new to to javascript so please take it easy :)
I'm trying to figure out the probability of 10 people picking the same random number (1 - 20).
When I run the code it returns the same answer every time. I think something is wrong in the 3rd for loop when comparing numbers. Some help would be much appreciated, I've been stuck on this for 3 days now :(
var counter = 0;
//Determine probability (percentage)
for (var i = 1; i <=100; i++) {
//Create array with 10 elements and assign each element with random integer (1 - 20)
for (var j = 1; j <= 10; j++) {
var rndNum = [j];
rndNum = Math.random();
rndNum = Math.floor(rndNum * 20) + 1;
}
//Increment counter if match is found
for (var p1 = 1; p1 <= 9; p1++) {
for (var p2 = p1 + 1; p2 <= 10; p2++) {
if (rndNum[p1] == rndNum[p2]) {
counter++;
}
}
}
}
document.write("The probability of a match is: " + counter + "%");
Your code to make an "array" of random numbers is part of the problem. rndNum only has one value (it's an array with only one item in it, and you're overwriting it each time). You need array.push() to add values to an array.
You want something more like this:
var rndNum = [];
for (var j = 1; j <= 10; j++) {
rndNum.push(Math.floor(Math.random()* 20) + 1);
}
You want to know the probability that twenty people will pick the same random number?
alert("The probability of a match is: " + (Math.pow(.1, 20)*100)+ "%");
Or you want to know the probability that any two of twenty people will pick the same number?
alert("The probability of a match is: " + (Math.pow(.9, 20)*100)+ "%");
Your for loop should also start at 0, not one (the first element in an array is array[0]:
for (var p1 = 0; p1 <= 8; p1++) {
for (var p2 = p1 + 1; p2 <= 9; p2++) {
if (rndNum[p1] == rndNum[p2]) {
counter++;
}
}
}
You also need to divide your results by 10 because you have 1,000 tests (if you're checking to see if two match). If you want to see if they all match you would need something like:
var ordered = rndNum.sort();
if(ordered[0] == ordered[9])
counter2++;
Here's a fiddle of the combined array declaration and match checkers.
I need to organize an array of strings of random length into the least number of new strings with a max size. Is there a function or something in javascript, or something that can be translated to javascript, that will do this?
For example, the new strings might have max lengths of 1000 characters. The array might have strings of lengths 100, 48, 29, etc. I would want to combine those strings into as few new strings as possible.
edit: Sorry if this doesn't make sense, I tried my best.
No standard method in Javascript, but plenty of theoretical work has been done on this (i.e. the bin packing problem).
http://en.wikipedia.org/wiki/Bin_packing_problem
Some sample pseudo code in the link - should be trivial to translate to javascript.
The algorithm shown isn't going to be optimal in every case. To find the optimal solution to your example you'll just need to iterate over every possibility which might not be that bad depending on how many strings you have.
For my own entertainment, I wrote a simple bin packing algorithm. I picked a simple algorithm which is to sort the input strings by length. Create a new bin. Put the first (longest remaining) string into the bin and then keep filling it up with the longest strings that will fit until no more strings will fit. Create a new bin, repeat. To test it, I allocate an array of strings of random lengths and use that as input. You can see the output visually here: http://jsfiddle.net/jfriend00/FqPKe/.
Running it a bunch of times, it gets a fill percentage of between 91-98%, usually around 96%. Obviously the fill percentage is higher if there are more short strings to fill with.
Here's the code:
function generateRandomLengthStringArrays(num, maxLen) {
var sourceChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY1234567890";
var sourceIndex = 0;
var result = [];
var len, temp, fill;
function getNextSourceChar() {
var ch = sourceChars.charAt(sourceIndex++);
if (sourceIndex >= sourceChars.length) {
sourceIndex = 0;
}
return(ch);
}
for (var i = 0; i < num; i++) {
len = Math.floor(Math.random() * maxLen);
temp = new String();
fill = getNextSourceChar();
// create string
for (var j = 0; j < len; j++) {
temp += fill;
}
result.push(temp);
}
return(result);
}
function packIntoFewestBins(input, maxLen) {
// we assume that none of the strings in input are longer than maxLen (they wouldn't fit in any bin)
var result = [];
// algorithm here is to put the longest string into a bin and
// then find the next longest one that will fit into that bin with it
// repeat until nothing more fits in the bin, put next longest into a new bin
// rinse, lather, repeat
var bin, i, tryAgain, binLen;
// sort the input strings by length (longest first)
input.sort(function(a, b) {return(b.length - a.length)});
while (input.length > 0) {
bin = new String(); // create new bin
bin += input.shift(); // put first one in (longest we have left) and remove it
tryAgain = true;
while (bin.length < maxLen && tryAgain) {
tryAgain = false; // if we don't find any more that fit, we'll stop after this iteration
binLen = bin.length; // save locally for speed/convenience
// find longest string left that will fit in the bin
for (i = 0; i < input.length; i++) {
if (input[i].length + binLen <= maxLen) {
bin += input[i];
input.splice(i, 1); // remove this item from the array
tryAgain = true; // try one more time
break; // break out of for loop
}
}
}
result.push(bin);
}
return(result);
}
var binLength = 60;
var numStrings = 100;
var list = generateRandomLengthStringArrays(numStrings, binLength);
var result = packIntoFewestBins(list, binLength);
var capacity = result.length * binLength;
var fillage = 0;
for (var i = 0; i < result.length; i++) {
fillage += result[i].length;
$("#result").append(result[i] + "<br>")
}
$("#summary").html(
"Fill percentage: " + ((fillage/capacity) * 100).toFixed(1) + "%<br>" +
"Number of Input Strings: " + numStrings + "<br>" +
"Number of Output Bins: " + result.length + "<br>" +
"Bin Legnth: " + binLength + "<br>"
);
I want to create an array of random/pseudo-random numbers using a seed. I want the very same array to be created when the same seed is used and I want to have little or no visible pattern in the array. I'm working in JavaScript.
This is the random function I'm using, which I'm quite happy with (sorry, I forgot who the original author is):
function random(seed) {
if (!seed) seed = new Date().getTime();
seed = (seed*9301+49297) % 233280;
return seed/(233280.0);
}
This is the array generation:
var superSeed = random();
var nRandom = 100;
var randomArray = new Array();
for (var i = 0 ; i < nRandom ; i++){
randomArray.push(random((superSeed*10)+ (i)));
}
Somehow the pattern seems to be quite similar, no matter how often I run it. This question seems to be similar, but since it's about matrixes, I don't understand what's being said.
Thanks!
Having worked on similar things before I think we can use a fairly simple series, which takes two initial values and then you can get a lot more.
var a1,b1;
function InitSequence(v1, v2) {
a1 = Math.pow(v1, 5) / Math.pow(v1, 3);
b1 = Math.pow(v2, 8);
lastrand = (a1 + b1) & 0x7fffffff;
}
function SequenceNext() {
var alast = a1;
var nextVal = (a1 + b1) & 0x7fffffff;
b1 = alast;
a1 = nextVal;
return nextVal;
}
Then use it like this:
InitSequence(75, 21);
for (var i = 0; i < 99; i++) {
v = SequenceNext();
}
I tested it like this:
var used = new Array();
InitSequence(75, 21); // any two values will do.
// fill 10k into array.
for (var i = 0; i < 9999; i++) {
v = SequenceNext();
if (undefined != used[v]) {
used[v]++;
} else used[v] = 1;
//document.write(i+": "+v+"<br>");
}
// see if there any duplicates.
var tdup = 0;
for (xx in used) {
ndup = used[xx];
if (ndup > 1) {
document.write("duplicated " + xx + " :" + ndup + "<br>");
tdup += ndup;
}
}
document.write("Total dups " + tdup + "<br>");
This is using the Fibonacci series, which in mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
. I'm starting with different values - (v1^5) / (v1^3) and v2 ^ 8; otherwise it would only ever be identical.
I like the "Super 7" PRNG. It is simple, fast (although the other answer with the fib. sequence is fast as well), and has the interesting property:
In the entire range -- albeit of a meager of 32k -- there are no duplicates using the "Super 7" PRNG.
Multiple 7's can be joined to increase the number of bits and/or provide multiple seeds. This non-duplication property can exposed or folded.
(The sequence of a PRNG is always the same given a starting seed: it's the distribution and cycle lengths that are interesting -- it is these properties that may make them ideal in different cases where "true randomness" isn't desired).
Happy coding.
Maybe you should try this
function s_random() {
s_random.m = 71402523; s_random.a = 409647; s_random.c = 1508892;
s_random.seed = (s_random.seed*s_random.a + s_random.c) % s_random.m;
return s_random.seed / s_random.m;
}
/*
generate IV
s_random.seed = Math.floor((new Date).getTime()/10000);
*/
s_random.seed = 130324232;
var CheckRandom = 4999999;
var PrintSamples = 100;
var used = new Array();
for (var i = 0; i < CheckRandom; i++) {
v = (Math.ceil(Math.sqrt(s_random())* 1000000000) * 8);
if (undefined != used[v]) {
used[v]++;
} else used[v] = 1;
if ( i< PrintSamples) document.write(i+": "+v+"");
}
/* see if there are any duplicates. */
var tdup = 0;
for (xx in used) {
ndup = used[xx];
if (ndup > 1) {
if (ndup < PrintSamples) document.write("duplicated " + xx + " :" + ndup + "");
tdup += ndup;
}
}
document.write("Total generated " + CheckRandom + "");
document.write("Total duplicates " + tdup + "");
Just got 5 million seeded, repeatable random numbers and no duplicates. Tested several times on Mac OS X with Safari.
Cheers,
Karl