Fill numbers from 1 to n,fast algorithm - javascript

I need algorithm what can fill string/array/etc by numbers from 1 to n; 1 <= 1 <= 10^8.
Time limit ≈ 2 seconds.
n = 100000000;
arr = [];
for (let i = 1;i <= n;i++){
arr.push(i)
}
console.log(arr)
If try like this it takes 33.785 seconds that too much

You make multiple reallocation of memory for string - this is rather long procedure.
If possible - preset list/array capacity, then fill it with values, rather than increment length one-by-one. In Python you can use list comprehension - perhaps JS has something alike.
For strings use a kind of StringBuilder if available.

Related

Find the sum of the digits in the number 100! in javascript

i am getting answer 659 but that one is wrong answer please check it one's.
this is my code
var fact=1;
for(var i=1;i<=100;i++){
fact = fact*i;
}
var sum = 0;
while (fact > 0) {
sum += fact % 10;
fact = Math.floor(fact / 10);
}
console.log(sum);
There's a syntax error in the definition of length - the var keyword should come before it, not after it, and a similar problem in the calculation of sum.
Regardless, I think that converting the number to a string is the hard way to go at it. You can use the % operator to get the last digit and divide the number by 10 (don't forget to floor!) until you're done with all the digits:
var sum = 0;
while (fact > 0) {
sum += fact % 10;
fact = Math.floor(fact / 10);
}
Cool. You've written a very sensible piece of code. But there are a couple things to think about. One is the gigantic size of 100!. If you go to a console and enter some code, you'll see this:
> fact=1
1
> for(i=1;i<=100;i++){fact *= i;}
9.33262154439441e+157
Crikey. 10 to the 157. Look up the largest integer js can display. It's much smaller! So if this is a programming assignment, you have to be more subtle.
Next, if you get the number, all 158 digits, and you want to add them using your strategy, you may need to convert the strings you get (a substring is a string, after all) to a Number.
But really, the question is, can you determine the sum of the digits without calculating the number?

Convert arbitary string to number between 0 and 1 in Javascript

I'm working with Youtube videos which have ids like 8DnKOc6FISU, rNsrl86inpo, 5qcmCUsw4EQ (i.e. 11 characters in the set A-Za-z0-9_-)
The goal is to convert each id to a colour (represented by the range 0-1), so they can be reliably charted.
According to this question these are 64 bit numbers. Given that:
I want to make full use of the colour space for any given set of videos
Colour perception isn't that accurate anyway
...it seems sensible to base this off the last 2-3 characters of the id.
My lead approach is a function I borrowed from here, which converts each character into a binary number like so:
function toBin(str){
var st,i,j,d;
var arr = [];
var len = str.length;
for (i = 1; i<=len; i++){
d = str.charCodeAt(len-i);
for (j = 0; j < 8; j++) {
st = d%2 == '0' ? "class='zero'" : ""
arr.push(d%2);
d = Math.floor(d/2);
}
}
}
But this leaves the question of how to convert this back to a float.
Any ideas for an elegant solution?
Many thanks for your help!
Knowing that system is base 64 (26+26+10+2), just read each symbol, add it to total and multiply result by 64 on each iteration. In the end you will have an integer number. Divide it by maximum value to normalize it to 0-1 range.
You'll start losing precision when your IDs approach 253 though, as that's maximum what JS can represent in integer precisely.
Alternatively you can count in floats from the very start by adding (letter_index / 64letter_position) for each position in line, but you'd be losing more precision in process.

percent chance logic issue/refactoring (javascript)

I have an array of numbers, each one of these number represents weight. the numbers in the array is between 0 and 1, and the total of these numbers adds up to 1. So if say array[1] is 0.6 then that represents I want it to show about 60% of the time. The array itself is not known to me so I don't know these numbers, they are user input for example.
I have a solution that will work but i don't know if it is the most efficient way to do this. My solution just seems very inefficient. Here it is
generate random number
copy this user input array into a new array and sort it from smallest to largest
compare the random number to numbers in this new array, so it would compare from the smallest in the array to the largest, when random number is smaller than the array number then I will store the array number into a variable say x and exit the loop
finally, i will compare x with the original array to figure out what the index of x is in the original array
this seems like a lot of work to do, is there a simpler solution? my head does not spin that fast
EDIT - the original array is not sorted in any way
EDIT 2 - Basically I am having trouble comparing this random number to the unsorted array. I need the unsorted to stay the same which is why I created that new array in my logic
If you have an array whose elements sum to 1, you can use the following algorithm:
Pick a uniformly distributed (pseuo)random number, r, between 0 and the sum of the weights.
For each weight,
If r is less than the weight, pick it and exit.
Otherwise subtract the weight from r, so it is now between 0 and the sum of the remaining weights.
Since r is always between 0 and the sum of the remaining weights, there is always a chance proportional to each weight that r is less than it when the loop reaches that weight.
In JavaScript:
var weights = [0.5, 0.15, 0.3, 0.05];
var index = weights.length - 1; // Last by default to avoid rounding error.
var r = Math.random();
for (var i = 0; i < a.length - 1; ++i) {
if (weights[i] > r) { index = i; break; }
// The rest of the array sums to
// 1 - sum(weights[0]..weights[i])
// so rescale r appropriately.
r -= weights[i];
}
will give you the desired distribution.
The trick is the r -= which makes sure that r is always between 0 and the sum of the unprocessed array elements.
You can test it at http://jsfiddle.net/KdKdb/

Javascript split string at 160 characters and add counter?

I am looking to split a string into multiple strings at 160 characters I thought easy enough var splits = myString.split(160);
but apparently that doesn't work anyway.
The other point is that I want to add a counter (android sms style).
so lets say we have this example string (237 characters)
hi there, this message is 237 characters long, which makes it much to
long for a single message, this string will be split up into multiple
messages... this is actually for an sms application hence the reason
we need to split the string.
The final output should be
hi there, this message is 237 characters long, which makes it much to long for a single
message, this string will be split up into multiple messages... thi(1/2)
s string will be split up into multiple
messages... this is actually for an sms application hence the reason
we need to split the string.(2/2)
Now if there was always going to be 9 or less messages I could just do
//ok, so the next line won't work, but it gets the point across...
var splits = mystring.split(155);
var s = splits.length;
for(var i = 0; i < s; i++)
splits[i] += '('+(i+1)+'/'+s+')';
but the issue is that there could be anywhere up to 15 messages, so the amount of characters appended on the end is inconsistent (we want to keep the character count as low as possible to 0 padding numbers less than 10 is not an option).
How can I do this?
http://jsfiddle.net/Lobstrosity/nwaYe/
It will cut off at 160 * 15 characters (since you implied that 15 was the limit). It sets both of those numbers as variables up top so you can fiddle with either one.
Update
New fiddle: http://jsfiddle.net/Lobstrosity/nwaYe/2/
It's ugly...but it works...
It figures out if the y in (x/y) is going to be one digit or two.
It uses a placeholder in the indicators while it builds up the actual message.
It replaces the placeholders.
Finally, it splits on charLimit.
I hope someone else figures out a cleaner way to do this...
I think your best choice for getting optimal messages (i.e. max length) may be to handle each class of max message length separately.
Handle the cases where you have less than ten messages with your current code, then extend that method to cover cases where you have up to 99 messages. If there's a chance of going over 100 messages, then you could extend further, but that sounds unlikely.
Here's a code sample:
if (mystring.length < (155 * 9)) {
var splits = mystring.split(155);
var s = splits.length;
for(var i = 0; i < s; i++)
splits[i] += '('+(i+1)+'/'+s+')';
} else if (mystring.length < (154*9)+(153 * 90)) {
var splits1 = mystring.substr(0,154*9).split(154);
var splits2 = mystring.substr(154*9).split(153);
var splits = [];
var s = splits1.length + splits2.length;
for (var i = 0; i < splits1.length; i++)
splits[i] = splits1[i] + '('+(i+1)+'/'+s+')';
for (var i = 10; i < splits2.length+10; i++)
splits[i] = splits2[i-10] + '('+(i+1)+'/'+s+')';
}

Chunk a string every odd and even position

I know nothing about javascript.
Assuming the string "3005600008000", I need to find a way to multiply all the digits in the odd numbered positions by 2 and the digits in the even numbered positions by 1.
This pseudo code I wrote outputs (I think) TRUE for the odd numbers (i.e. "0"),
var camid;
var LN= camid.length;
var mychar = camid.charAt(LN%2);
var arr = new Array(camid);
for(var i=0; i<arr.length; i++) {
var value = arr[i]%2;
Alert(i =" "+value);
}
I am not sure this is right: I don't believe it's chunking/splitting the string at odd (And later even) positions.
How do I that? Can you please provide some hints?
/=================================================/
My goal is to implement in a web page a validation routine for a smartcard id number.
The logic I am trying to implement is as follows:
· 1) Starting from the left, multiply all the digits in the odd numbered positions by 2 and the digits in the even numbered positions by 1.
· 2) If the result of a multiplication of a single digit by 2 results in a two-digit number (say "7 x 2 = 14"), add the digits of the result together to produce a new single-digit result ("1+4=5").
· 3) Add all single-digit results together.
· 4) The check digit is the amount you must add to this result in order to reach the next highest multiple of ten. For instance, if the sum in step #3 is 22, to reach the next highest multiple of 10 (which is 30) you must add 8 to 22. Thus the check digit is 8.
That is the whole idea. Google searches on smartcard id validation returned nothing and I am beginning to think this is overkill to do this in Javascript...
Any input welcome.
var theArray = camid.split(''); // create an array entry for each digit in camid
var size = theArray.length, i, eachValue;
for(i = 0; i < size; i++) { // iterate over each digit
eachValue = parseInt(theArray[i], 10); // test each string digit for an integer
if(!isNaN(eachValue)) {
alert((eachValue % 2) ? eachValue * 2 : eachValue); // if mod outputs 1 / true (due to odd number) multiply the value by 2. If mod outputs 0 / false output value
}
}
I discovered that what I am trying to do is called a Luhn validation.
I found an algorithm right here.
http://sites.google.com/site/abapexamples/javascript/luhn-validation
Thanks for taking the time to help me out. Much appreciated.
It looks like you might be building to a Luhn validation. If so, notice that you need to count odd/even from the RIGHT not the left of the string.

Categories

Resources