http://www.leemon.com/crypto/BigInt.js
I am using the leemon bigint.js library, but I am having trouble figuring out how to divide one big number by another. Here is what I have so far:
var a = str2bigInt("100",10);
var b = int2bigInt("5", 10);
var result = [];
var r = [];
divide_(a,b,result,r)
alert(bigInt2str(result,10));
but when I alert(result) the output is 0. The result should be 20? Can anybody see what I am doing wrong?
Cheers
I suppose the line
var b = int2bigInt("5", 10);
should be
var b = str2bigInt("5", 10);
The function int2bigInt expects an integer, not a string.
Apparently, this BigInt.js library expects the result arrays to already have sufficient length to store the result; using empty arrays doesn't work.
This code however works as expected:
var a = str2bigInt("100",10);
var b = int2bigInt("5", 10);
var result = new Array(2);
var r = new Array(2);
divide_(a,b,result,r);
alert(bigInt2str(result,10));
Related
I'm making a prep course for a bootcamp - yes, n00b over here! - and I'm stuck in this particular exercise about String Methods
I need to manipulate this original string 'supercalifragilisticexpialidocious' and obtain the following version: docious-ali-expi-istic-fragil-cali-rupus
I've tried this:
var bigWord = 'supercalifragilisticexpialidocious';
var newWord1 = bigWord.slice(27);
var newWord2 = bigWord.slice(24,27);
var newWord3 = bigWord.slice(20,24);
var newWord4 = bigWord.slice(15,20);
var newWord5 = bigWord.slice(9,15);
var newWord6 = bigWord.slice(9,5);
var newWord7 = bigWord.slice(5,9);
var newWord8 = bigWord.charAt(4);
var newWord9 = bigWord.slice(1,2);
var newWord10 = bigWord.charAt(2);
var newWord11 = bigWord.slice(32);
console.log(newWord1,newWord2,newWord3,newWord4,newWord5,newWord6,newWord7,newWord8,newWord9,newWord10,newWord11);
Does anybody have a hint for me? Can someone help me out?
Cheers!
Here is a code snipet that works. It does not answer your question though:
var bigWord = 'supercalifragilisticexpialidocious';
var newWord1 = bigWord.slice(27);
var newWord2 = bigWord.slice(24,27);
var newWord3 = bigWord.slice(20,24);
var newWord4 = bigWord.slice(15,20);
var newWord5 = bigWord.slice(9,15);
var newWord6 = bigWord.slice(5,9);
var newWord7 = bigWord.charAt(4) + bigWord.slice(1,2) + bigWord.charAt(2) + bigWord.slice(32);
console.log([newWord1,newWord2,newWord3,newWord4,newWord5,newWord6,newWord7].join("-"));
The problems are:
you used .slice(9,5) for word 6 which is incorrect, because 9 is behind the 5 and therefore newWord6 did not get the correct result, but "" (empty string)
you did not add up word 7 to a whole, but printed its elements separately
you have to print minus characters in between
either by putting + "-" + between every variables
or by adding up an array like mine and use the join() operator
I would go for some Regexep stuff
const original = 'supercalifragilisticexpialidocious';
const expected = 'docious-ali-expi-istic-fragil-cali-repus';
// the most common way to reverse a string is to explode it to an array and use the standard reverse method and then joining it back again as a string
function reverseString(str) {
return str.split("").reverse().join("");
}
// the replacer method do the job of concataining words joining them by dash and call the reverse method for the last matched word.
function replacer(match, p1, p2, p3, p4, p5, p6, p7, offset, string) {
return [p7, p6, p5, p4, p3, p2, reverseString(p1)].join('-');
}
// pick the words by block of letters
const actual = original.replace(/(\w{5})(\w{4})(\w{6})(\w{5})(\w{4})(\w{3})(\w{7})/, replacer);
console.log(expected === actual);
I tried to make a simple example for you while keeping things somewhat dynamic so you can learn.
Assuming you want the words sliced from the end of the string to the start of it and then combined back together in reverse with a - then all you need to 'hardcode' is the length of each word to slice (from the start to the end) and then loop through that and slice out your words. So if you want to turn supercalifragilisticexpialidocious into docious-ali-expi-istic-fragil-cali-super you can do this:
var bigWord = 'supercalifragilisticexpialidocious';
var slices = [5, 4, 6, 5, 4, 3, 7];
var words = [], lastSlice = 0;
slices.forEach(slice => {
words.push(bigWord.slice(lastSlice, lastSlice + slice))
lastSlice += slice;
});
// Reverse the sliced words and join them back together with -
words = words.reverse().join('-');
console.log(words); // outputs docious-ali-expi-istic-fragil-cali-super
var bigWord = 'supercalifragilisticexpialidocious';
var newWord1 = bigWord.slice(27);
var newWord2 = bigWord.slice(24,27);
var newWord3 = bigWord.slice(20,24);
var newWord4 = bigWord.slice(15,20);
var newWord5 = bigWord.slice(9,15);
var newWord6 = bigWord.slice(5,9);
var newWord7 = bigWord.charAt(4) + bigWord.slice(1,2) + bigWord.charAt(2) + bigWord.slice(32);
var newBigWord =(newWord1+'-'+newWord2+'-'+newWord3+'-'+newWord4+'-'+newWord5+'-'+newWord6+'-'+newWord7);
console.log(newBigWord);
I have a function that I have modified to get a string (which consists of zeros and ones only).
The string (timesheetcoldata):
100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000
The string items (the numbers one and zero) will change every time the function is run.
It will always be the same length.
I have made the string above easier to see what I am trying to achieve.
I want to return the first character and then every 24th character (as in the variable colsCount in the function).
so, in the example above, it would return something like: 111111
I then want to convert these characters to numbers (something like [1, 1, 1, 1, 1, 1]).
I then want to sum these number together (so it would return, in the example: 6).
I then want to check if the returned number matches the variable: rowsCount
or true if it does, false if it does not.
My function:
$("#J_timingSubmit").click(function(ev){
var sheetStates = sheet.getSheetStates();
var rowsCount = 6;
var colsCount = 24;
var timesheetrowsdata = "";
var timesheetcoldata = "";
for(var row= 0, rowStates=[]; row<rowsCount; ++row){
rowStates = sheetStates[row];
timesheetrowsdata += rowStates+(row==rowsCount-1?'':',');
}
timesheetcoldata = timesheetrowsdata.replace(/,/g, '');
console.log(timesheetcoldata);
});
Thank you very much to both Rajesh and MauriceNino (and all other contributers).
With their code I was able to come up with the following working function:
$("#J_timingSubmit").click(function(ev){
var sheetStates = sheet.getSheetStates();
var rowsCount = 6;
var timesheetrowsdata = "";
var timesheetcoldata = "";
for(var row= 0, rowStates=[]; row<rowsCount; ++row){
rowStates = sheetStates[row];
timesheetrowsdata += rowStates+(row==rowsCount-1?'':',');
}
timesheetcoldata = timesheetrowsdata.replace(/,/g, '');
var count = 0;
var list = [];
for(var i = 0; i< timesheetcoldata.length; i+=24) {
const num1 = Number(timesheetcoldata.charAt(i));
list.push(num1);
count += num1;
}
let isSameAsRowsCount = count == rowsCount;
console.log('Is Same? ', isSameAsRowsCount);
});
You can always rely on traditional for for such action. Using functional operations can be more readable but will be more time consuming(though not by much).
You can try this simple algo:
Create a list that will hold all numbers and a count variable to hold sum.
Loop over string. As string is fixed, you can set the increment factor to the count(24).
Convert the character at given index and save it in a variable.
Push this variable in list and also compute sum at every interval.
At the end of this loop, you have both values.
var string = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
var count = 0;
var list = [];
for(var i = 0; i< string.length; i+=24) {
const num1 = Number(string.charAt(i));
list.push(num1);
count += num1;
}
console.log(list, count)
Here is a step by step explanation, on what to do.
Use match() to get every nth char
Use map() to convert your array elements
Use reduce() to sum your array elements
Everything needed to say is included in code comments:
const testData = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
// Step 1) Create array of numbers from string
const dataArr = testData.match(/.{1,24}/g) // Split on every 24th char
.map(s => Number(s[0])) // Only take the first char as a Number
console.log(dataArr);
// Step 2) Sum array Numbers
let dataSum = dataArr.reduce((a, b) => a + b); // Add up all numbers
console.log(dataSum);
// Step 3) Compare your variables
let rowsCount = 123; // Your Test variable
let isSameAsRowsCount = dataSum == rowsCount;
console.log('Is Same? ', isSameAsRowsCount);
As #Jaromanda mentioned, you can use the following to done this.
const string = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
const value = string.split('').filter((e,i)=> !(i%24)).reduce((acc,cur)=> acc+ (+cur), 0);
console.log(value);
I'm doing some simple math in Javascript, but my equation's result is drastically different than what it should be. The math is:
3.05+(((0.32*0)+3.28)+(1+(0.19*0))*(2.66*1^2))*1;
When I did it out by hand, and then used Wolfram Alpha (https://www.wolframalpha.com/) I get the correct result of 8.99. However, when I use the equation in Javascript I mysteriously get 6.33
The actual equation looks like
VO2move = VO2rest+(((C1*g2)+VO2walkmin)+(1+(C2*g2))*(C3*s2^2))*t2;
but I removed all the variables in an attempt to debug (I thought it might be some error where I needed parseInt)
Here are the whole functions for reference
function calc(){
var temp = 0;
var total = 0;
for(i = 0; i<sArr.length; i++){
total = total + calc2(i);
}
var o = document.getElementById("output");
o.value = total;
}
function calc2(i){
var s = document.getElementById("s"+i);
var g = document.getElementById("g"+i);
var t = document.getElementById("t"+i);
var VO2walkmin = 3.28;
var VO2rest = 3.05;
var C1 = 0.32;
var C2 = 0.19;
var C3 = 2.66;
var Cdecline = 0.73;
var s2 = s.value;
var g2 = g.value;
var t2 = t.value;
var negGrade = g.value;
if(g2 < 0){g2 = 0};
//VO2move = ((C1 * g2)+VO2walkmin)+((1+(C2*g2))*(C3*s2^2)); //ORIGINAL TRANSCRIPTION
//VO2move = VO2rest+(((C1*g2)+VO2walkmin)+(1+(C2*g2))*(C3*s2^2))*t2; // TRANSLATED FROM COPY PASTE
VO2move = 3.05+(((0.32*0)+3.28)+(1+(0.19*0))*(2.66*1^2))*1; // COPY - PASTED FROM EXCEL
return VO2move;
}
Even naked numbers I still get the output of 6.33. I'm totally puzzled, and any help is appreciated.
You need to take the power (exponentiation) operator ** instead of the bitwise XOR operator ^.
console.log(3.05+(((0.32*0)+3.28)+(1+(0.19*0))*(2.66*1**2))*1);
Instead of "var instance = ..." adding the two values it concatenates them. Can anyone suggest what I need to fix?
I'm trying to add "var startingEmail" value and "var k".
Thank you for your help!
var startingEmail = sheet.getRange("C2").getDisplayValue();
var numEmails = sheet.getRange("E2").getDisplayValue();
var max = numEmails;
for (var k = 0; k<max; ++k){
var threads = GmailApp.getInboxThreads(startingEmail,max)[k]; //get max 50 threads starting at most recent thread
var messages = threads.getMessages()[0];
var sndr;
var rcpnt;
var srAry = [];
var sndr = messages.getFrom().replace(/^.+<([^>]+)>$/, "$1"); //http://stackoverflow.com/questions/26242591/is-there-a-way-to-get-the-specific-email-address-from-a-gmail-message-object-in
var sndrLower = sndr.toLowerCase;
var rcpnt = messages.getTo().replace(/^.+<([^>]+)>$/, "$1");
var rcpntLower = rcpnt.toLowerCase;
var cc = messages.getCc().replace(/^.+<([^>]+)>$/, "$1");
var ccLower = cc.toLowerCase;
//srAry.push(sndr);
//srAry.push(rcpnt);
//srAry.push(cc);
var isIn = joinAddr.search(sndr || rcpnt);
if(isIn == -1){
var instance = k;
I can't see the example in your code but it sounds like you can just wrap Number() around your variable and it will perform the type conversion so the code will perform the math instead of concatenating as strings.
So i have this string
first €999, second €111
Im trying to make an array that looks like this (numbers after every €)
999,111
Edit:
Yes i have tried to split it but wont work. i tried to look it up on google and found something with indexof but that only returned the number of the last €.
rowData[2].split('€').map(Number);
parseInt(rowData[2].replace(/[^0-9\.]/g, ''), 10);
split(rowData[2].indexOf("€") + 1);
The numbers are variable.
var input ="first €999, second €111";
var output=[];
var arr = input.split(",");
for(var i=0;i<arr.length;i++)
{
output.push(parseInt(arr[i]));
}
var output_string = output.stingify();
console.log(output); //Output Array
console.log(output_string); //Output String
If the numbers will always be of 3 digits in length, you can do this. If not, you need to specify a bit more.
var string = "€999, second €111";
var temp = [];
var digitArray = [];
temp = string.split(",");
for(var i=0;i<temp.length,i++){
digitArray.push(temp[i].substring(temp[i].indexOf("€"),3));
}
//digitArray now contains [999,111];
Edit, based on your requirement of variable digit lengths
var string = "€999, second €111, third €32342";
var temp = [];
var digitArray = [];
temp = string.split(",");
for(var i=0;i<temp.length,i++){
digitArray.push(temp[i].replace(/^\D+/g, '')); //Replace all non digits with empty.
}
//digitArray now contains [999,111,32342]