javascript random 8digits in specific number - javascript

I'm trying to random 8 digits number 0-7 , but without the 8 and 9
this is what I've done, but I can't exclude the 8 and 9
var b = Math.floor(Math.random()*90000000) + 10000000;
console.log(b)
is there any quick for random the exact 8 digits exclude number? or do I really have to random one by one and += until 8 digits ?

Convert to octal (which contains only the digits 0-7) and trim to the desired length:
b.toString(8).substr(0, 8)

You could get first the max number of the octal system with 8 places and use the decimal system for generating the random value and convert it back to the wanted system.
var max = parseInt(100000000, 8);
console.log(('0000000' + Math.floor(Math.random() * max).toString(8)).slice(-8));

You need a number of 8 digits in base 8.
This means you're looking for a (decimal) number between 8^7 and 8^8-1, converted to base 8.
This should do the trick :
// initialize min and max values
var vmin = Math.pow(8,7);
var vmax = Math.pow(8,8)-1;
// compute random number within range
var dec = Math.floor(Math.random()*(vmax-vmin))+vmin;
// convert to base 8
console.log(dec.toString(8));

Perhaps you would want something more like this:
var b = Math.floor(Math.random()*8);
console.log(b);

Related

Is there a function that returns the number of characters in BigNumber.js?

I know about decimalPlaces:
const number = new BigNumber(100.5254);
number.decimalPlaces(); // 4
And precision:
const number = new BigNumber(100.5254);
number.precision(); // 7
But I couldn't find any function that returns only the number of characteristics. That is, in this example, 3 ("1", "0" and "0").
Is there something for this?
It seems there isn't one, as of Nov 2019 at least, but you can subtract the decimal places from the total precision to get the digits before the dot:
const number = new BigNumber(100.5254);
const digitsBeforeDot = number.precision(true) - number.decimalPlaces();
// prints 3
Note that:
If d (the first parameter of the precision function) is true then any trailing zeros of the integer part of a number are counted as significant digits, otherwise they are not.
See the docs:
decimalPlaces()
precision()

Generate big numbers with Math random in Javascript

I need to generate 26 digit numbers with Math.random, but when I use this:
Math.floor(Math.random() * 100000000000000000000000000) + 900000000000000000000000000
I gets 9.544695043285823e+26
Modern browsers support BigInt and bigint primitive type and we can combine it with a random generated array containing 8 bytes (the sizeof bigint is 8 bytes (64 bits)).
1. Generating Random BigInt Performance Wise
We can generate a random hex string of 16 characters length and apply it directly to BigInt:
const hexString = Array(16)
.fill()
.map(() => Math.round(Math.random() * 0xF).toString(16))
.join('');
const randomBigInt = BigInt(`0x${hexString}`);
// randomBigInt will contain a random Bigint
document.querySelector('#generate').addEventListener('click', () => {
const output = [];
let lines = 10;
do {
const hexString = Array(16)
.fill()
.map(() => Math.round(Math.random() * 0xF).toString(16))
.join('');
const number = BigInt(`0x${hexString}`);
output.push(`${
number.toString().padStart(24)
} : 0x${
hexString.padStart(16, '0')
}`);
} while (--lines > 0);
document.querySelector('#numbers').textContent = output.join('\n');
});
<button id="generate">Generate</button>
<pre id="numbers"><pre>
2. Generating Random BigInt from random bytes array
If we want to use Uint8Array or if we want more control over the bits manipulation, we can combine Array.prototype.fill with Array.prototype.map to generate an array containing 8 random byte number values (beware this is around 50% slower than the above method):
const randomBytes = Array(8)
.fill()
.map(() => Math.round(Math.random() * 0xFF));
// randomBytes will contain something similar to this:
// [129, 59, 98, 222, 20, 7, 196, 244]
Then we use Array.prototype.reduce to initialize a BigInt of zero value and left shift each randum byte value its position X 8 bits and applying bitwise or to the current value of each reduce iteration:
const randomBigInt = randomBytes
.reduce((n, c, i) => n | BigInt(c) << BigInt(i) * 8n, 0n);
// randomBigInt will contain a random Bigint
Working example generating 10 random BigInt values
document.querySelector('#generate').addEventListener('click', () => {
const output = [];
let lines = 10;
do {
const number = Array(8)
.fill()
.map(() => Math.round(Math.random() * 0xFF))
.reduce((n, c, i) => n | BigInt(c) << BigInt(i) * 8n, 0n);
output.push(`${
number.toString().padStart(24)
} : 0x${
number.toString(16).padStart(16, '0')
}`);
} while (--lines > 0);
document.querySelector('#numbers').textContent = output.join('\n');
});
<button id="generate">Generate</button>
<pre id="numbers"><pre>
Floating point numbers in JavaScript (and a lot of other languages) can contain only about 15.955 digits without losing precision. For bigger numbers you can look into JS libraries, or concatenate few numbers as strings. For example:
console.log( Math.random().toString().slice(2, 15) + Math.random().toString().slice(2, 15) )
Your question seems to be an XY problem where what you really want to do is generate a sequence of 26 random digits. You don't necessarily have to use Math.random. Whenever one mentions randomness it's important to specify how that randomness is distributed, otherwise you could end up with a paradox.
I'll assume you want each of the 26 digits to be independently randomly chosen uniformly from each of the 10 digits from 0 to 9, but I can also see a common interpretation being that the first digit must not be 0, and so that digit would be chosen uniformly from numbers 1 to 9.
Other answers may tempt you to choose a random bigint value using what amounts to random bits, but their digits will not be randomly distributed in the same way, since their maximum value is not a power of 10. For a simple example consider that a random 4 bit binary value in decimal will range from 00 to 15, and so the second digit will have a 12/16(=75%) chance of being 0 to 5, though it should be 60%.
As for an implementation, there's many ways to go about it. The simplest way would be to append to a string 26 times, but there are more potentially efficient ways that you could investigate for yourself if you find the performance isn't adequate. Math.random has a roughly uniform distribution from 0 to 1, but by being double precision it only has 15 or so significant decimal digits to offer us, so for each call to Math.random we should be able to retrieve up to 15 out of 26 decimal digits. Using this fact, I would suggest the following compromise on ease of readability and efficiency:
function generate26Digits() {
const first13 = Math.floor(Math.random() * Math.pow(10, 13)).toFixed(0).padStart(13, "0");
const next13 = Math.floor(Math.random() * Math.pow(10, 13)).toFixed(0).padStart(13, "0");
return first13 + next13;
}
console.log(generate26Digits())
This solution is not cryptographically secure however, and so I will direct readers to use Crypto.getRandomValues if you need more security for this for some reason.
If you then want to do math on this number as well without losing precision, you will have to use bigint types as others have suggested.
If I use a 6 decillion LG about 72.9 million out of 300 but when I switch to 10 centillion it comes like this 10 ^ 999 - 99999 + 26 just like how 9 - 9 - 9 - 9 - googolplex is equal to 0 googolplex

Javascript split integer and add decimal point

My integer value is 1210 and i want split this integer like 1 | 210 .Have to add decimal point on middle.
Eg:
var integer=1210;
Split this integer and add decimal value like this 1.210
Why don't you just divide the number by 1000
var x = 1210;
var y = 1210/1000; //1.210 number
var z = y+""; // 1.120 will be string here
console.log(y); // Will output 1.210
If you're always dealing with 4 digit numbers, dividing by 1000 will work (as mentioned in another answer) but you'll need to use toFixed to make sure javascript doesn't remove trailing zeros:
var x = 1210;
(x / 1000).toFixed(3) // => "1.210"
(x / 1000) + "" // => "1.21"
More generically you could use:
x=prompt('enter an integer');
xl=x.toString().length-1
alert((x/Math.pow(10,xl)).toFixed(xl));
(just make sure you enter an integer, preferably +ve, at the prompt)

parseInt() doesn't regard leading zeros, even with radix

When I want to convert a binary string to a base 10 decimal (Like this: parseInt('0001010', 2)), Javascript returns a decimal number, but a version in which the leading zeros mentioned in the example above have been disregarded. Is there any way to fix this?
So supposing you have the number '00000101101101':
var number = '00000101101101';
var length = number.length;
var decimal_number = parseInt(number, 2);
// going back
var new_number = decimal_number.toString(2);
var new_length = new_number.length;
var n_zeros = length - new_length;
var zeros = (n_zeros >= 2 ? Array(n_zeros+1).join("0") : "0");
new_number = zeros + new_number;
The decimal representation has no way to keep track of leading zeros. If you wish to keep the leading zeros in the result, you need a fundamentally different approach (e.g. keeping the output as a string).
Alternatively, if you know the width of the result a priori, you could just pad it with leading zeros on output.

Compressing a Hex String in JavaScript/NodeJS

My app generates links, which contain hex string like: 37c1fbcabbc31f2f8d2ad31ceb91cd8d0d189ca5963dc6d353188d3d5e75b8b3e401d4e74e9b3e02efbff0792cda5c4620cb3b1f84aeb47b8d2225cd40e761a5. I would really like to make them shorter, like the solution mentioned for Ruby in Compressing a hex string in Ruby/Rails.
Is there a way to do this in JavaScript/NodeJS?
node int-encoder does this, using the strategy already mentioned.
it also supports large numbers
npm install int-encoder
var en = require('int-encoder');
//simple integer conversion
en.encode(12345678); // "ZXP0"
en.decode('ZXP0'); // 12345678
//convert big hex number using optional base argument
en.encode('e6c6b53d3c8160b22dad35a0f705ec09', 16); // 'hbDcW9aE89tzLYjDgyzajJ'
en.decode('hbDcW9aE89tzLYjDgyzajJ', 16); // 'e6c6b53d3c8160b22dad35a0f705ec09'
You could use toString and parseInt method, that basically are doing the same thing of the methods you mentioned in the link:
var hexString = "4b3fc1400";
var b36 = parseInt(hexString, 16).toString(36); // "9a29mgw"
And to convert it back, you just need to do the opposite:
hexString = parseInt(b36, 36).toString(16); // "4b3fc1400"
The only problem with your string, is that is too big to be threat as number in JavaScript. You should split them in chunk. JavaScript's numbers are accurate up to 2^53 (plus sign), so the max positive number you can handle is 0x20000000000000 (in hexadecimal, that is 9007199254740992 in decimal); you can use the accuracy to handle the chunk:
var hexString = "37c1fbcabbc31f2f8d2ad31ceb91cd8d0d189ca5963dc6d353188d3d5e75b8b3e401d4e74e9b3e02efbff0792cda5c4620cb3b1f84aeb47b8d2225cd40e761a5"
var b36 = "", b16 = "";
var chunk, intChunk;
// 14 is the length of 0x20000000000000 (2^53 in base 16)
for (var i = 0, max = 14; i < hexString.length; i += max) {
chunk = hexString.substr(i, max);
intChunk = parseInt(chunk, 16);
if (intChunk.toString(16) !== chunk) {
intChunk = parseInt(hexString.substr(i, max - 1), 16);
i -= 1;
}
b36 += intChunk.toString(36)
}
// 11 is the length of 2gosa7pa2gv (2^53 in base 36)
for (var i = 0, max = 11; i < b36.length; i += max ) {
chunk = b36.substr(i, max);
intChunk = parseInt(chunk, 36);
if (intChunk.toString(36) !== chunk) {
intChunk = parseInt(b36.substr(i, max - 1), 36);
i -= 1;
}
b16 += intChunk.toString(16)
}
console.log(hexString);
console.log(b36);
console.log(b16);
Update: You could also use a base 62 instead of 36 to compress more, but notice that JS supports up to base 36, so you need to implement that personal notation manually (I believe there are already some implementation around).
The simplest and fastest thing to do is define a set of 64 safe characters for use in the URL, such as A-Z, a-z, 0-9, _, and $. Then encode every three hex digits (4 bits each) into two safe characters (6 bits each). This requires no multiplication and division, and it can be used on arbitrarily long strings.
You will need to pick a 65th character to use at the end of the string to indicate if the last four-bit piece is used or not. Otherwise you will have an ambiguity for character strings with an even number of characters. Let's call it 2n. Then there are either 3n-1 or 3n hex digits encoded within, but there is no way to tell which. You can follow the sequence with a special character to indicate one of those cases. E.g. a '.' (period).
Note: The last few characters picked here for the set differ from Base64 encoding, since URLs have their own definition of safe punctuation characters. See RFC 1738.

Categories

Resources