how to get uint256_t upper and lower part in nodejs/javascript, - javascript

i have equivalent c++ but not sure how to implement this in javascript/nodejs.
c++:
template <unsigned int BITS>
enum { WIDTH = BITS / 32 };
uint32_t pn[WIDTH];
uint256 seed = "00000800ab9d2c5409a9b4dea2aa6f8471cecc41b35706e6d6155098e5f3595d";
uint64_t Get64(int n = 0) const
{
return pn[2 * n] | (uint64_t)pn[2 * n + 1] << 32;
}
uint64_t first = seed.Get64(0) % 6 + 1;
uint64_t second = seed.Get64(1) % 6 + 1;
able to get uint64_t first with below. but not sure how to implement it for second one.
//uint64_t first = seed.Get64(0) % 6 + 1;
var bigInt = require("big-integer");
var hash = bigInt("00000800ab9d2c5409a9b4dea2aa6f8471cecc41b35706e6d6155098e5f3595d",16);
console.log(hash.and(new bigInt("ffffffffffffffff", 16)).mod(6) + 1)
//result of first = 6

How to do it with javascript "native" BigInt
const get64 = (value, n=0) => (value >> BigInt(64*n)) & 0xffffffffffffffffn;
const toNumber = value => +value.toString();
var hash = 0x00000800ab9d2c5409a9b4dea2aa6f8471cecc41b35706e6d6155098e5f3595dn;
var first = toNumber(get64(hash, 0) % 6n + 1n);
var second = toNumber(get64(hash, 1) % 6n + 1n);
console.log(first, second)
alternatively, you can do what many consider a big no-no and extend BigInt prototype - usually I'd suggest extending the BigInt class, but, that's not possible as far as I can tell (since new BigInt is not supported)
BigInt.prototype.get64 = function (n=0) {
return (this >> BigInt(64 * n)) & ((1n<<64n) - 1n);
}
BigInt.prototype.toNumber = function () {
return +this.toString();
}
var hash = 0x00000800ab9d2c5409a9b4dea2aa6f8471cecc41b35706e6d6155098e5f3595dn;
var first = (hash.get64(0) % 6n + 1n).toNumber();
var second = (hash.get64(1) % 6n + 1n).toNumber();
console.log(first, second)

Related

A code wars challenge

I have been struggling with this challenge and can't seem to find where I'm failing at:
Some numbers have funny properties. For example:
89 --> 8¹ + 9² = 89 * 1
695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2
46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p we want to find a positive integer k, if it exists, such as the sum of the digits of n taken to the successive powers of p is equal to k * n. In other words:
Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k
If it is the case we will return k, if not return -1.
Note: n, p will always be given as strictly positive integers.
digPow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1
digPow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k
digPow(695, 2) should return 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2
digPow(46288, 3) should return 51 since 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
I'm new with javascript so there may be something off with my code but I can't find it. My whole purpose with this was learning javascript properly but now I want to find out what I'm doing wrong.I tried to convert given integer into digits by getting its modulo with 10, and dividing it with 10 using trunc to get rid of decimal parts. I tried to fill the array with these digits with their respective powers. But the test result just says I'm returning only 0.The only thing returning 0 in my code is the first part, but when I tried commenting it out, I was still returning 0.
function digPow(n, p){
// ...
var i;
var sum;
var myArray= new Array();
if(n<0)
{
return 0;
}
var holder;
holder=n;
for(i=n.length-1;i>=0;i--)
{
if(holder<10)
{
myArray[i]=holder;
break;
}
myArray[i]=holder%10;
holder=math.trunc(holder/10);
myArray[i]=math.pow(myArray[i],p+i);
sum=myArray[i]+sum;
}
if(sum%n==0)
{
return sum/n;
}
else
{
return -1;
}}
Here is the another simple solution
function digPow(n, p){
// convert the number into string
let str = String(n);
let add = 0;
// convert string into array using split()
str.split('').forEach(num=>{
add += Math.pow(Number(num) , p);
p++;
});
return (add % n) ? -1 : add/n;
}
let result = digPow(46288, 3);
console.log(result);
Mistakes
There are a few problems with your code. Here are some mistakes you've made.
number.length is invalid. The easiest way to get the length of numbers in JS is by converting it to a string, like this: n.toString().length.
Check this too: Length of Number in JavaScript
the math object should be referenced as Math, not math. (Note the capital M) So math.pow and math.trunc should be Math.pow and Math.trunc.
sum is undefined when the for loop is iterated the first time in sum=myArray[i]+sum;. Using var sum = 0; instead of var sum;.
Fixed Code
I fixed those mistakes and updated your code. Some parts have been removed--such as validating n, (the question states its strictly positive)--and other parts have been rewritten. I did some stylistic changes to make the code more readable as well.
function digPow(n, p){
var sum = 0;
var myArray = [];
var holder = n;
for (var i = n.toString().length-1; i >= 0; i--) {
myArray[i] = holder % 10;
holder = Math.trunc(holder/10);
myArray[i] = Math.pow(myArray[i],p+i);
sum += myArray[i];
}
if(sum % n == 0) {
return sum/n;
} else {
return -1;
}
}
console.log(digPow(89, 1));
console.log(digPow(92, 1));
console.log(digPow(46288, 3));
My Code
This is what I did back when I answered this question. Hope this helps.
function digPow(n, p){
var digPowSum = 0;
var temp = n;
while (temp > 0) {
digPowSum += Math.pow(temp % 10, temp.toString().length + p - 1);
temp = Math.floor(temp / 10);
}
return (digPowSum % n === 0) ? digPowSum / n : -1;
}
console.log(digPow(89, 1));
console.log(digPow(92, 1));
console.log(digPow(46288, 3));
You have multiple problems:
If n is a number it is not going to have a length property. So i is going to be undefined and your loop never runs since undefined is not greater or equal to zero
for(i=n.length-1;i>=0;i--) //could be
for(i=(""+n).length;i>=0;i--) //""+n quick way of converting to string
You never initialize sum to 0 so it is undefined and when you add the result of the power calculation to sum you will continually get NaN
var sum; //should be
var sum=0;
You have if(holder<10)...break you do not need this as the loop will end after the iteration where holder is a less than 10. Also you never do a power for it or add it to the sum. Simply remove that if all together.
Your end code would look something like:
function digPow(n, p) {
var i;
var sum=0;
var myArray = new Array();
if (n < 0) {
return 0;
}
var holder;
holder = n;
for (i = (""+n).length - 1; i >= 0; i--) {
myArray[i] = holder % 10;
holder = Math.trunc(holder / 10);
myArray[i] = Math.pow(myArray[i], p + i);
sum = myArray[i] + sum;
}
if (sum % n == 0) {
return sum / n;
} else {
return -1;
}
}
Note you could slim it down to something like
function digPow(n,p){
if( isNaN(n) || (+n)<0 || n%1!=0) return -1;
var sum = (""+n).split("").reduce( (s,num,index)=>Math.pow(num,p+index)+s,0);
return sum%n ? -1 : sum/n;
}
(""+n) simply converts to string
.split("") splits the string into an array (no need to do %10 math to get each number
.reduce( function,0) call's the array's reduce function, which calls a function for each item in the array. The function is expected to return a value each time, second argument is the starting value
(s,num,index)=>Math.pow(num,p+index+1)+s Fat Arrow function for just calling Math.pow with the right arguments and then adding it to the sum s and returning it
I have created a code that does exactly what you are looking for.The problem in your code was explained in the comment so I will not focus on that.
FIDDLE
Here is the code.
function digPow(n, p) {
var m = n;
var i, sum = 0;
var j = 0;
var l = n.toString().length;
var digits = [];
while (n >= 10) {
digits.unshift(n % 10);
n = Math.floor(n / 10);
}
digits.unshift(n);
for (i = p; i < l + p; i++) {
sum += Math.pow(digits[j], i);
j++;
}
if (sum % m == 0) {
return sum / m;
} else
return -1;
}
alert(digPow(89, 1))
Just for a variety you may do the same job functionally as follows without using any string operations.
function digPow(n,p){
var d = ~~Math.log10(n)+1; // number of digits
r = Array(d).fill()
.map(function(_,i){
var t = Math.pow(10,d-i);
return Math.pow(~~((n%t)*10/t),p+i);
})
.reduce((p,c) => p+c);
return r%n ? -1 : r/n;
}
var res = digPow(46288,3);
console.log(res);

Can't get BBP formula to work in nodejs

I've been trying to make a little program that can compute the n-th digit of pi.
After a few searches I've found that the most common formula is the BBP formula, wich is n-th digit = 16^-n[4/(8n + 1)-2/(8n + 4)-1/(8n + 5)-1/(8n + 6)].
The output is in base 16.
My code is the following:
function run(n) {
return Math.pow(16, -n) * (4 / (8 * n + 1) - 2 / (8 * n + 4) - 1 / (8 * n + 5) - 1 / (8 * n + 6));
}
function convertFromBaseToBase(str, fromBase, toBase) {
var num = parseInt(str, fromBase);
return num.toString(toBase);
}
for (var i = 0; i < 10; i++) {
var a = run(i);
console.log(convertFromBaseToBase(a, 16, 10));
}
So far, my output is the following:
1:3
2:0
3:0
4:0
5:1
6:7
7:3
8:1
9:7
10:3
Obviously, these are not the 10 first digits of PI.
My understanding is that values get rounded too often and that causes huge innacuracy in the final result.
However, I could be wrong, that's why I'm here to ask if I did anything wrong or if it's nodejs's fault. So I would loove if one of you guys have the answer to my problem!
Thanks!!
Unfortunately, 4/(8n + 1) - 2/(8n + 4) - 1/(8n + 5) - 1/(8n + 6) does not directly return the Nth hexadecimal digit of pi. I don't blame you, I made the same assumption at first. Although all the terms do indeed sum to pi, each individual term does not represent an individual hexadecimal digit. As seen here, the algorithm must be rewritten slightly in order to function correctly as a "digit spigot". Here is what your new run implementation ought to look like:
/**
Bailey-Borwein-Plouffe digit-extraction algorithm for pi
<https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula#BBP_digit-extraction_algorithm_for_.CF.80>
*/
function run(n) {
var partial = function(d, c) {
var sum = 0;
// Left sum
var k;
for (k = 0; k <= d - 1; k++) {
sum += (Math.pow(16, d - 1 - k) % (8 * k + c)) / (8 * k + c);
}
// Right sum. This converges fast...
var prev = undefined;
for(k = d; sum !== prev; k++) {
prev = sum;
sum += Math.pow(16, d - 1 - k) / (8 * k + c);
}
return sum;
};
/**
JavaScript's modulus operator gives the wrong
result for negative numbers. E.g. `-2.9 % 1`
returns -0.9, the correct result is 0.1.
*/
var mod1 = function(x) {
return x < 0 ? 1 - (-x % 1) : x % 1;
};
var s = 0;
s += 4 * partial(n, 1);
s += -2 * partial(n, 4);
s += -1 * partial(n, 5);
s += -1 * partial(n, 6);
s = mod1(s);
return Math.floor(s * 16);
}
// Pi in hex is 3.243f6a8885a308d313198a2e037073...
console.log(run(0) === 3); // 0th hexadecimal digit of pi is the leading 3
console.log(run(1) === 2);
console.log(run(2) === 4);
console.log(run(3) === 3);
console.log(run(4) === 15); // i.e. "F"
Additionally, your convertFromBaseToBase function is more complicated than it needs to be. You have written it to accept a string in a specific base, but it is already being passed a number (which has no specific base). All you should really need is:
for (var i = 0; i < 10; i++) {
var a = run(i);
console.log(a.toString(16));
}
Output:
3
2
4
3
f
6
a
8
8
8
I have tested this code for the first 30 hexadecimal digits of pi, but it might start to return inaccurate results once Math.pow(16, d - 1 - k) grows beyond Number.MAX_SAFE_INTEGER, or maybe earlier for other reasons. At that point you may need to implement the modular exponentiation technique suggested in the Wikipedia article.

in javascript is it possible to assign a arithmetic operand to a variable?

I know I can simply use an if else statement to have the math done for me, and could even create a function that could be called either way depending on the need, but I am trying to based on math simply store either + or - as a variable so it can execute
for example
plusOrMinus = +
5 + plusOrMinus + 5 = 10
I'm not sure what kind of situation you're in, but wouldn't multiplying by 1 or -1 suffice?
plusOrMinus = 1
5 + (plusOrminus * 5) = 10
plusOrMinus = -1
5 + (plusOrminus * 5) = 0
No, but it is possible to create a function that wraps the given operator(s):
function add(a, b) { return a + b };
function sub(a, b) { return a - b };
var op = add; // look, functions are just objects!
op(5, 5) // -> 10
var op = sub;
op(7, 3) // -> 4
Well, how does this help us? Just expand it!
function fold (arr, fn) {
var r = arr[0];
for (var i = 1; i < arr.length - 1; i++) {
r = fn(r, arr[i]);
}
return r;
}
fold([1,2,3], add) // -> 6
You can store 1 or -1, and multiply, like this:
var plusOrMinus;
var Result;
plusOrMinus = 1;
Result = (5 + 5) * plusOrMinus; // 10
plusOrMinus = -1;
Result = (5 + 5) * plusOrMinus; // -10
You probably need eval()
plusOrMinus = '+'
eval(5+plusorMinus+5);

less than 10 add 0 to number [duplicate]

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 4 years ago.
How can I modify this code to add a 0 before any digits lower than 10
$('#detect').html( toGeo(apX, screenX) + latT +', '+ toGeo(apY, screenY) + lonT );
function toGeo(d, max) {
var c = '';
var r = d/max * 180;
var deg = Math.floor(r);
c += deg + "° ";
r = (r - deg) * 60;
var min = Math.floor(r);
c += min + "′ ";
r = (r - min) * 60;
var sec = Math.floor(r);
c += sec + "″";
return c;
}
So the outpout would change from
4° 7′ 34″W, 168° 1′ 23″N
to
04° 07′ 34″W, 168° 01′ 23″N
Thanks for your time
You can always do
('0' + deg).slice(-2)
See slice():
You can also use negative numbers to select from the end of an array
Hence
('0' + 11).slice(-2) // '11'
('0' + 4).slice(-2) // '04'
For ease of access, you could of course extract it to a function, or even extend Number with it:
Number.prototype.pad = function(n) {
return new Array(n).join('0').slice((n || 2) * -1) + this;
}
Which will allow you to write:
c += deg.pad() + '° '; // "04° "
The above function pad accepts an argument specifying the length of the desired string. If no such argument is used, it defaults to 2. You could write:
deg.pad(4) // "0045"
Note the obvious drawback that the value of n cannot be higher than 11, as the string of 0's is currently just 10 characters long. This could of course be given a technical solution, but I did not want to introduce complexity in such a simple function. (Should you elect to, see alex's answer for an excellent approach to that).
Note also that you would not be able to write 2.pad(). It only works with variables. But then, if it's not a variable, you'll always know beforehand how many digits the number consists of.
Make a function that you can reuse:
function minTwoDigits(n) {
return (n < 10 ? '0' : '') + n;
}
Then use it in each part of the coordinates:
c += minTwoDigits(deg) + "° ";
and so on.
if(myNumber.toString().length < 2)
myNumber= "0"+myNumber;
or:
return (myNumber.toString().length < 2) ? "0"+myNumber : myNumber;
You can always do
('0' + deg).slice(-2)
If you use it very often, you may extend the object Number
Number.prototype.pad = function(n) {
if (n==undefined)
n = 2;
return (new Array(n).join('0') + this).slice(-n);
}
deg.pad(4) // "0045"
where you can set any pad size or leave the default 2.
You can write a generic function to do this...
var numberFormat = function(number, width) {
return new Array(+width + 1 - (number + '').length).join('0') + number;
}
jsFiddle.
That way, it's not a problem to deal with any arbitrarily width.
Hope, this help:
Number.prototype.zeroFill= function (n) {
var isNegative = this < 0;
var number = isNegative ? -1 * this : this;
for (var i = number.toString().length; i < n; i++) {
number = '0' + number;
}
return (isNegative ? '-' : '') + number;
}
Here is Genaric function for add any number of leading zeros for making any size of numeric string.
function add_zero(your_number, length) {
var num = '' + your_number;
while (num.length < length) {
num = '0' + num;
}
return num;
}
I was bored and playing around JSPerf trying to beat the currently selected answer prepending a zero no matter what and using slice(-2). It's a clever approach but the performance gets a lot worse as the string gets longer.
For numbers zero to ten (one and two character strings) I was able to beat by about ten percent, and the fastest approach was much better when dealing with longer strings by using charAt so it doesn't have to traverse the whole string.
This follow is not quit as simple as slice(-2) but is 86%-89% faster when used across mostly 3 digit numbers (3 character strings).
var prepended = ( 1 === string.length && string.charAt( 0 ) !== "0" ) ? '0' + string : string;
$('#detect').html( toGeo(apX, screenX) + latT +', '+ toGeo(apY, screenY) + lonT );
function toGeo(d, max) {
var c = '';
var r = d/max * 180;
var deg = Math.floor(r);
if(deg < 10) deg = '0' + deg;
c += deg + "° ";
r = (r - deg) * 60;
var min = Math.floor(r);
if(min < 10) min = '0' + min;
c += min + "′ ";
r = (r - min) * 60;
var sec = Math.floor(r);
if(sec < 10) sec = '0' + sec;
c += sec + "″";
return c;
}
A single regular expression replace should do it:
var stringWithSmallIntegers = "4° 7′ 34″W, 168° 1′ 23″N";
var paddedString = stringWithSmallIntegers.replace(
/\d+/g,
function pad(digits) {
return digits.length === 1 ? '0' + digits : digits;
});
alert(paddedString);
shows the expected output.

IP-addresses stored as int results in overflow?

I'm writing a chat-server in node.js, and I want to store connected users IP-addresses in a mysql database as (unsigned) integers.
I have written a javascript method to convert an ip-address as string to an integer. I get some strange results however.
Here is my code:
function ipToInt(ip) {
var parts = ip.split(".");
var res = 0;
res += parseInt(parts[0], 10) << 24;
res += parseInt(parts[1], 10) << 16;
res += parseInt(parts[2], 10) << 8;
res += parseInt(parts[3], 10);
return res;
}
When I run call the method as ipToInt("192.168.2.44"); the result I get is -1062731220.
It seems like an overflow has occurred, which is strange, because the expected output (3232236076) is inside the number range in javascript (2^52).
When I inspect -1062731220 in binary form, I can see the 3232236076 is preserved, but filled with leading 1's.
I'm not sure, but I think the problem is with signed vs. unsigned integers.
Can any of you explain what is going on?
And possibly how to parse -1062731220 back to an string ip?
Why is the converted IP negative?
It's NOT an overflow. The first part of your IP address is 192 which converts to 11000000 in binary. You then shift that all the way to the left. When there is a 1 in the leftmost position of a 32 bit number, it's negative.
How do you convert back to a string?
Do the same thing you did to convert from a string but in reverse. Shift right (and mask)!
function intToIP(int) {
var part1 = int & 255;
var part2 = ((int >> 8) & 255);
var part3 = ((int >> 16) & 255);
var part4 = ((int >> 24) & 255);
return part4 + "." + part3 + "." + part2 + "." + part1;
}
Why reinvent the wheel? From Google:
OR, you can use what I found here:
http://javascript.about.com/library/blipconvert.htm
function dot2num(dot)
{
var d = dot.split('.');
return ((((((+d[0])*256)+(+d[1]))*256)+(+d[2]))*256)+(+d[3]);
}
function num2dot(num)
{
var d = num%256;
for (var i = 3; i > 0; i--)
{
num = Math.floor(num/256);
d = num%256 + '.' + d;
}
return d;
}
The result of the "<<" operator is always a signed, 32-bit integer, as per the spec.
When you shift back, use ">>>" to do an unsigned right shift.
You might also find this pattern useful:
ip.toLong = function toInt(ip){
var ipl=0;
ip.split('.').forEach(function( octet ) {
ipl<<=8;
ipl+=parseInt(octet);
});
return(ipl >>>0);
};
ip.fromLong = function fromInt(ipl){
return ( (ipl>>>24) +'.' +
(ipl>>16 & 255) +'.' +
(ipl>>8 & 255) +'.' +
(ipl & 255) );
};
If you're using something like node.js where you can add functionality through something like Npm then you can simply do:
npm install ip
To get that functionality from the source which is here:
https://github.com/indutny/node-ip/blob/master/lib/ip.js
You will also get a bunch of other IP utility functions with that.
You shifted left to get the original number - which is just 4 sets of bits regardless of the sign.
Shift right to get back to the IP. Doesn't matter what the sign is.
const ip2int = (x) => (x.split('.').reduce((a, v) => ((a << 8) + (+v)), 0) >>> 0);
One-Liner:
const ipToLong = ip => ip.split('.').map(parseFloat).reduce((total, part) => total * 256 + part);
Use this
function num2string(ip) {
return [24,16,8,0].map(n => (ip >> n) & 0xff).join(".")
}
function string2num(ip) {
return ip.split(".").reduce((sum,x,i) => sum + (x << 8*(3-i)), 0)
}
IP Addresses in the V4 space are unsigned 32 bit numbers, hence the IP address of FF.FF.FF.FF is 2^32 and cannot be greater then that number. Please see:
This stack overflow article on the same subject
To turn that number back into an IP address you must break the number down into its 4 parts since each byte is one octet of the address so convert the number to hex and then parse out each pair. You may or may not have to add a leading zero for the first octet.
Additionally you may have to deal with byte order of the integer ( endien issues ) but since most systems are intel based these days you might not have to deal with that.
var aaa = Number("0b"+ "192.168.2.44".split(".").map(
function(dec){
return ("00000000" + Number(dec).toString(2)).slice(-8);
}).join(""));
aaa.toString(2).match(/.{1,8}/g).map(
function(bin){
return Number("0b"+bin);
}).join(".");
I revised Evan's final answer a bit, particularly dot2num. It functions the same but might be more readable and is marginally slower.
function ip2num(ip) {
var parts = ip.split('.');
var num = 0;
num += d[0] * Math.pow(2, 24);
num += d[1] * Math.pow(2, 16);
num += d[2] * Math.pow(2, 8);
num += d[3];
return num;
}
function num2ip(num) {
var ip = num % 256;
for (var i=3; i > 0; i--) {
num = Math.floor(num / 256);
ip = num % 256 + '.' + ip;
}
return ip;
}
Try this solution, it might help:
function IpToInteger(ipAddr)
{
var parts = ipAddr.split('.');
return (((parts[0] ? parts[0] << 24 : 0) |
(parts[1] ? parts[1] << 16 : 0) |
(parts[2] ? parts[2] << 8 : 0) |
(parts[3])) >>> 0);
}
function IpAddressToLong(ip){
return ip.split('.').map((octet, index, array) => {
return parseInt(octet) * Math.pow(256, (array.length - index - 1));
}).reduce((prev, curr) => {
return prev + curr;
});
}
Taken from repo
function ip2num(ip) {
var d = ip.split(".");
var num = 0;
num += Number(d[0]) * Math.pow(256, 3);
num += Number(d[1]) * Math.pow(256, 2);
num += Number(d[2]) * Math.pow(256, 1);
num += Number(d[3]);
return num;
}
function num2ip(num) {
var ip = num % 256;
for (var i = 3; i > 0; i--) {
num = Math.floor(num / 256);
ip = (num % 256) + "." + ip;
}
return ip;
}
console.log(ip2num("192.168.0.1"));
console.log(num2ip(3232235521))
<h1>YOU IS WELCOME</h1>

Categories

Resources