This is my code
function convertToCurr(value) {
var x = value.toString().length;
var z = x % 3;
var a = 0;
if (z == 0) {
a = (x / 3) - 1;
}
else {
a = (x / 3);
}
var last = 0;
var vals = [];
var i;
for (i = 1; i <= a; i++) {
steps = 3;
start = x - steps * i;
end = start + steps;
last = end - steps;
vals.unshift(value.toString().slice(start, end));
}
vals.unshift("R " + value.toString().slice(0, last));
return vals.join();
}
basicIO.write(convertToCurr(input));
context.log.INFO("log data");
}
These are my outputs
{"output":"R 1,000,000,.00","log":["log data"]}
{"output":"R 1,000,.00","log":["log data"]}
I need to exctract the last "," so that the amounts make sense
The most straightforward solution is to perform a String.prototype.replace() on the final join().
function convertToCurr(value) {
var x = value.toString().length;
var z = x % 3;
var a = 0;
if (z == 0) {
a = (x / 3) - 1;
}
else {
a = (x / 3);
}
var last = 0;
var vals = [];
var i;
for (i = 1; i <= a; i++) {
steps = 3;
start = x - steps * i;
end = start + steps;
last = end - steps;
vals.unshift(value.toString().slice(start, end));
}
vals.unshift("R " + value.toString().slice(0, last));
return vals.join().replace(',.', '.');
}
console.log(convertToCurr(10000.75));
console.log(convertToCurr(10.01));
console.log(convertToCurr(1000));
console.log(convertToCurr(7002344));
It should be noted that replace() only replaces a single instance of the substring you provide it in the input string, but this doesn't matter here since ,. only appears in your output string one time.
function convertToCurr(value) {
var x = value.toString().length;
var z = x % 3;
var a = 0;
var combinedString; // holds string value after join
if (z == 0) {
a = x / 3 - 1;
} else {
a = x / 3;
}
var last = 0;
var vals = [];
var i;
for (i = 1; i <= a; i++) {
steps = 3;
start = x - steps * i;
end = start + steps;
last = end - steps;
vals.unshift(value.toString().slice(start, end));
}
vals.unshift("R " + value.toString().slice(0, last));
combinedString = vals.join(); // join array into string
return combinedString.replace(",.", "."); // replace ,. with .
}
console.log(convertToCurr(50000000.15));
Related
I have a simple code to fill an array with some conditions but each time I get this error :
Uncaught TypeError: int_part is not a function
what's the problem here? what I'm missing?
here is the code:
var totalSlides = 4; // total number of slides we have
var lastSlideInt = 20; // numbers of review interactions on the last slide
var n = totalSlides - 1;
var x = lastSlideInt / (n * (n + 1) / 2);
var cal = [];
for (var i = 1; i < lastSlideInt; i++) {
cal.push(i * x);
}
var indexs = [];
var minus = [];
//
var sum = 0;
var floatSum = 0;
for (var i = 0; i < cal.length; i++) {
sum += cal[i];
if (sum >= 1) {
var pusher = int_part(sum) + int_part(floatSum);
floatSum += float_part(sum);
minus.push(pusher);
indexs.push(i);
}
}
//
function int_part(y) {
return int_part = Math.trunc(y);
float_part = Number((y - int_part).toFixed(2));
}
function float_part(d) {
int_part = Math.trunc(d);
return float_part = Number((d - int_part).toFixed(2));
}
console.log(int_part(0.2));
I think the error should be somewhere on the if statement:
if (sum >= 1){
var pusher = int_part(sum) + int_part(floatSum);
floatSum += float_part(sum);
minus.push(pusher);
indexs.push(i);
}
You are reassigning the functions int_part and float_part to number inside the body of function. You should only return the values.
var totalSlides = 4; // total number of slides we have
var lastSlideInt = 20; // numbers of review interactions on the last slide
var n = totalSlides - 1;
var x = lastSlideInt / (n*(n+1)/2);
var cal = [];
for (var i = 1; i < lastSlideInt; i++ ){
cal.push(i * x);
}
var indexs = [];
var minus = [];
//
var sum = 0;
var floatSum = 0;
for (var i = 0; i < cal.length; i++) {
sum += cal[i];
if (sum >= 1){
var pusher = int_part(sum) + int_part(floatSum);
floatSum += float_part(sum);
minus.push(pusher);
indexs.push(i);
}
}
//
function int_part(y){
return Math.trunc(y);
}
function float_part(d){
let int_part = Math.trunc(d);
return Number((d-int_part).toFixed(2));
}
console.log(int_part(0.2));
https://codepen.io/aholston/pen/ZJbrjd
The codepen link has commented code as well as actual instructions in HTML
Otherwise.... what I ultimately have to do is write a function that takes two params(a and b) and takes all the numbers between those two params (a-b) and put every number that can be added to the consecutive fowers and be equal to that number into a new array. Ex: 89 = 8^1 + 9^2 = 89 or 135 = 1^1 + 3^2 + 5^3 = 135
function sumDigPow(a, b) {
// Your code here
var numbers = [];
var checkNum = [];
var finalNum = [];
var total = 0;
for (var i = 1; i <= b; i++) {
if (i >= a && i <= b) {
numbers.push(i);
}
}
for (var x = 0; x < numbers.length; x++) {
var checkNum = numbers[x].toString().split('');
if (checkNum.length == 1) {
var together = parseInt(checkNum);
finalNum.push(together);
} else if (checkNum.length > 1) {
var together = checkNum.join('');
var togNumber = parseInt(together);
for (var y = checkNum.length; y > 0; y--) {
total += Math.pow(checkNum[y - 1], y);
}
if (total == togNumber) {
finalNum.push(togNumber);
}
}
}
return finalNum;
}
try this:
function listnum(a, b) {
var finalNum = [];
for (var i = a; i <= b; i++) {
var x = i;
var y = i;
var tot = 0;
j = i.toString().length;
while (y) {
tot += Math.pow((y%10), j--);
y = Math.floor(y/10);
}
if (tot == x)
finalNum.push(i);
}
return finalNum;
}
console.log(listnum(1, 200));
Okay, after debugging this is what I learned.
for (var y = checkNum.length; y > 0; y--) {
total += Math.pow(checkNum[y - 1], y);
}
if (total == togNumber) {
finalNum.push(togNumber);
}
}
}
return finalNum;
}
Everytime this loop happened, I neglected to reset the 'total' variable back to 0. So I was never getting the right answer for my Math.pow() because my answer was always adding to the previous value of total. In order to fix this, I added var total = 0; after i decided whether or not to push 'togNumber' into 'finalNum.' So my code looks like this..
for (var y = checkNum.length; y > 0; y--) {
total += Math.pow(checkNum[y - 1], y);
}
if (total == togNumber) {
finalNum.push(togNumber);}
}
var total = 0;
}
return finalNum;
}
I want to find the minimum number of characters of the first string that needs to be changed to enable me to make it an anagram of the second string.
1st problem it always return -1
function anagram(s) {
if (s % 2 == 0) {
var len = s.legnth;
var diff = [];
for (var x = 0; x < len / 2; x++) {
var y = s[x]++;
}
for (var x = len / 2; x < s.legnth; x++) {
var z = s[x]++;
}
y = y.sort().splice(",").tostring();
z = y.sort().splice(",").tostring();
for (var x = 0; i < z.length; x++) {
if (y[x] != z[x]) {
diff.push(y[x]);
}
}
return diff.length;
} else {
return -1;
}
}
function main() {
var q = parseInt(readLine());
for (var a0 = 0; a0 < q; a0++) {
var s = readLine();
var result = anagram(s);
process.stdout.write("" + result + "\n");
}
}
I have two text boxes. Each will take input up to thousand digits.
Now i want to add these two numbers. My question is what data type should i use to store the result?
I have tried this:
<script>
var x = 'Thousand digit of number'
var y = 'Thousand digit of number'
var z = x + y
</script>
but i am getting result in exponential form. How to store the result and display it?
Yet another solution, because it's faster and cleaner.
function add(A, B) {
const AL = A.length
const BL = B.length
const ML = Math.max(AL, BL)
let carry = 0, sum = ''
for (let i = 1; i <= ML; i++) {
let a = +A.charAt(AL - i)
let b = +B.charAt(BL - i)
let t = carry + a + b
carry = t/10 |0
t %= 10
sum = (i === ML && carry)
? carry*10 + t + sum
: t + sum
}
return sum
}
> add(
'9999999999999999999999999999999999999999999999999999999999999999999999999999',
'999999999999999999999999999999999999999'
)
> "10000000000000000000000000000000000000999999999999999999999999999999999999998"
Use BigInt as described here: https://stackoverflow.com/a/56370672/641913
const z = BigInt(x) + BigInt(y);
console.log(z.toString());
Here is another solution not so different from others you can find in the internet (consider that it doesn't work with negative numbers!):
function sums(arg1, arg2) {
var sum = "";
var r = 0;
var a1, a2, i;
// Pick the shortest string as first parameter and the longest as second parameter in my algorithm
if (arg1.length < arg2.length) {
a1 = arg1;
a2 = arg2;
}
else {
a1 = arg2;
a2 = arg1;
}
a1 = a1.split("").reverse();
a2 = a2.split("").reverse();
// Sum a1 and a2 digits
for (i = 0; i < a2.length; i++) {
var t = ((i < a1.length) ? parseInt(a1[i]) : 0) + parseInt(a2[i]) + r;
sum += t % 10;
r = t < 10 ? 0 : Math.floor(t / 10);
}
// Append the last remain
if (r > 0)
sum += r;
sum = sum.split("").reverse();
// Trim the leading "0"
while (sum[0] == "0")
sum.shift();
return sum.length > 0 ? sum.join("") : "0";
}
// Test
function testEquals(expected, actual) {
if (expected == actual)
console.log("OK: " + expected);
else
console.error("ERROR: " + expected + " != " + actual);
}
testEquals("100", sums("99", "1"));
testEquals("100", sums("00099", "0001"));
testEquals("10000000000", sums("9999999999", "1"));
testEquals("10000010101", sums("9999999999", "10102"));
testEquals("0", sums("0", "0"));
testEquals("1", sums("0", "1"));
testEquals("9", sums("8", "1"));
testEquals("9", sums("1", "8"));
testEquals("10000000000000000000000000000000000000000", sums("9999999999999999999999999999999999999999", "1"));
Input the numbers as string and add each characters each other as array something like this:
function add() {
document.getElementById("demo").innerHTML = "";
var x = document.getElementById("txt1").value;
var y = document.getElementById("txt2").value;
var len;
var lenx = x.length;
var leny = y.length;
var x1,y1,rem,div=0;
if(lenx>leny) len = lenx; else len = leny;
for(var i=0;i<len;i++){
if(i>=lenx) x1 = 0;
else x1 = parseInt(x[lenx-i-1]);
if(i>=leny) y1 = 0;
else y1 = parseInt(y[leny-i-1]);
rem = (x1+y1+div)%10;
div = Math.floor((x1 + y1+div)/10);
document.getElementById("demo").innerHTML = rem + document.getElementById("demo").innerHTML;
}
if(div>0){
document.getElementById("demo").innerHTML = div + document.getElementById("demo").innerHTML;
}
}
Here the code: https://jsfiddle.net/mtsL1k2x/5/
Note: this is only for natural numbers. You can modify depending on your inputs
Either use a big number library like https://mathjs.org/docs/datatypes/bignumbers.html , or you can use something lighter weight (but easy to understand) like http://www.discoversdk.com/knowledge-base/arbitrary-length-integer-addition-in-javascript
Well, if you want to do this without using BigInt or any third-party Library, then I don't think you need to convert to an array, you can use the charAt() function to add the individual characters at each point in the string. You would have to use the for loop starting from its maximum value and reducing till its lowest. The code snippet is below;
function add(a, b) {
let sum='';
let z,x;
let r=0;
if (a.length>=b.length){
z=a;
x=b;
}
else{
z=b;
x=a;
};
let p=x.length;
for (let i=z.length;i>0;i--){
let t=((p>0)?parseInt(x.charAt(p-1)):0)+parseInt(z.charAt(i-1))+r;
sum=(t%10)+sum;
r=t<10?0:Math.floor(t/10);
p=p-1;
};
if (r>0){sum=r+sum};
return sum;
};
function add(a, b) {
a = a.split("").reverse();
b = b.split("").reverse();
let maxLen=Math.max(a.length, b.length);
let sum = [];
let remainder = 0;
for (let i = 0; i < maxLen; i++) {
let x = parseInt(a[i]) ? parseInt(a[i]) : 0;
let y = parseInt(b[i]) ? parseInt(b[i]) : 0;
let digit = (x + y + remainder) % 10;
remainder = Math.floor((x + y + remainder) / 10);
sum.unshift(digit);
}
if (remainder) {sum.unshift(remainder)}
return sum.join("");
}
function add(x, y) {
//this function adds two extremely large numbers, negative and/or positive
var temp, borrow=false, bothNeg=false, oneNeg=false, neg=false;
if (x < 0 && y < 0) { bothNeg = true; x = -x; y = -y; }
else if (x < 0 || y < 0) {
oneNeg = true;
if (Math.abs(x) == Math.abs(y)) { x = 0; y = 0; }
else if (x < 0 && Math.abs(x) > Math.abs(y)) { neg = true; x = -x; y = -y; }
else if (x < 0 && Math.abs(x) < Math.abs(y)) { temp = y; y = x; x = temp; }
else if (y < 0 && Math.abs(x) < Math.abs(y)) { neg = true; temp = y; y = -x; x = -temp; }
}
x = parseInt(x*1000000000/10).toString();
y = parseInt(y*1000000000/10).toString();
var lenx=x.length, leny=y.length, len=(lenx>leny)?lenx:leny, sum="", div=0, x1, y1, rem;
for (var i = 0; i < len; i++) {
x1 = (i >= lenx) ? 0 : parseInt(x[lenx-i-1]);
y1 = (i >= leny) ? 0 : parseInt(y[leny-i-1]);
y1 = (isNaN(y1)) ? 0 : y1;
if (oneNeg) y1 = -y1;
if (borrow) x1 = x1 - 1;
if (y < 0 && x1 > 0 && Math.abs(x1) >= Math.abs(y1)) { borrow=false; div=0; }
if (y < 0 && y1 <= 0 && (x1 < 0 || Math.abs(x1) < Math.abs(y1))) { borrow=true; rem=(x1+y1+div+10)%10; div=10; }
else { rem=(x1+y1+div)%10; div=Math.floor((x1+y1+div)/10); }
sum = Math.abs(rem).toString() + sum;
}
if (div > 0) sum = div.toString() + sum;
sum = parseFloat(sum*10/1000000000);
if (bothNeg || neg) sum = -sum;
return sum;
}
<body>
<p>Click the button to calculate x.</p>
<button onclick="myFunction()">Try it</button>
<br/>
<br/>Enter first number:
<input type="text" id="txt1" name="text1">Enter second number:
<input type="text" id="txt2" name="text2">
<p id="demo"></p>
<script>
function myFunction() {
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
var x = +y + +z;
document.getElementById("demo").innerHTML = x;
}
</script>
https://jsfiddle.net/Sanjeevgaut/mtsL1k2x/
Is there a way to calculate pi in Javascript? I know there you can use Math.PI to find pie like this:
var pie = Math.PI;
alert(pie); // output "3.141592653589793"
but this is not accurate. What I want is to be able to calculate it, to have as many digits as you want, not anything like pie = 3.141592.... But still, what I want is not have just have some more digits, but as much as you can (like having one thousand digits, but I need more).
Here is an implementation of a streaming algorithm described by Jeremy Gibbons in Unbounded Spigot Algorithms for the Digits of Pi (2004), Chaper 6:
function * generateDigitsOfPi() {
let q = 1n;
let r = 180n;
let t = 60n;
let i = 2n;
while (true) {
let digit = ((i * 27n - 12n) * q + r * 5n) / (t * 5n);
yield Number(digit);
let u = i * 3n;
u = (u + 1n) * 3n * (u + 2n);
r = u * 10n * (q * (i * 5n - 2n) + r - t * digit);
q *= 10n * i * (i++ * 2n - 1n);
t *= u;
}
}
// Demo
let iter = generateDigitsOfPi();
let output = document.querySelector("div");
(function displayTenNextDigits() {
let digits = "";
for (let i = 0; i < 10; i++) digits += iter.next().value;
output.insertAdjacentHTML("beforeend", digits);
scrollTo(0, document.body.scrollHeight);
requestAnimationFrame(displayTenNextDigits);
})();
div { word-wrap:break-word; font-family: monospace }
<div></div>
I found this code on this website:
mess = "";
Base = Math.pow(10, 11);
cellSize = Math.floor(Math.log(Base) / Math.LN10);
a = Number.MAX_VALUE;
MaxDiv = Math.floor(Math.sqrt(a));
function makeArray(n, aX, Integer) {
var i = 0;
for (i = 1; i < n; i++) aX[i] = null;
aX[0] = Integer
}
function isEmpty(aX) {
var empty = true
for (i = 0; i < aX.length; i++)
if (aX[i]) {
empty = false;
break
}
return empty
}
function Add(n, aX, aY) {
carry = 0
for (i = n - 1; i >= 0; i--) {
aX[i] += Number(aY[i]) + Number(carry);
if (aX[i] < Base) carry = 0;
else {
carry = 1;
aX[i] = Number(aX[i]) - Number(Base)
}
}
}
function Sub(n, aX, aY) {
for (i = n - 1; i >= 0; i--) {
aX[i] -= aY[i];
if (aX[i] < 0) {
if (i > 0) {
aX[i] += Base;
aX[i - 1]--
}
}
}
}
function Mul(n, aX, iMult) {
carry = 0;
for (i = n - 1; i >= 0; i--) {
prod = (aX[i]) * iMult;
prod += carry;
if (prod >= Base) {
carry = Math.floor(prod / Base);
prod -= (carry * Base)
} else carry = 0;
aX[i] = prod
}
}
function Div(n, aX, iDiv, aY) {
carry = 0;
for (i = 0; i < n; i++) {
currVal = Number(aX[i]) + Number(carry * Base);
theDiv = Math.floor(currVal / iDiv);
carry = currVal - theDiv * iDiv;
aY[i] = theDiv
}
}
function arctan(iAng, n, aX) {
iAng_squared = iAng * iAng;
k = 3;
sign = 0;
makeArray(n, aX, 0);
makeArray(n, aAngle, 1);
Div(n, aAngle, iAng, aAngle);
Add(n, aX, aAngle);
while (!isEmpty(aAngle)) {
Div(n, aAngle, iAng_squared, aAngle);
Div(n, aAngle, k, aDivK);
if (sign) Add(n, aX, aDivK);
else Sub(n, aX, aDivK);
k += 2;
sign = 1 - sign
}
mess += "aArctan=" + aArctan + "<br>"
}
function calcPI(numDec) {
var ans = "";
t1 = new Date();
numDec = Number(numDec) + 5;
iAng = new Array(10);
coeff = new Array(10);
arrayLength = Math.ceil(1 + numDec / cellSize);
aPI = new Array(arrayLength);
aArctan = new Array(arrayLength);
aAngle = new Array(arrayLength);
aDivK = new Array(arrayLength);
coeff[0] = 4;
coeff[1] = -1;
coeff[2] = 0;
iAng[0] = 5;
iAng[1] = 239;
iAng[2] = 0;
makeArray(arrayLength, aPI, 0);
makeArray(arrayLength, aAngle, 0);
makeArray(arrayLength, aDivK, 0);
for (var i = 0; coeff[i] != 0; i++) {
arctan(iAng[i], arrayLength, aArctan);
Mul(arrayLength, aArctan, Math.abs(coeff[i]));
if (coeff[i] > 0) Add(arrayLength, aPI, aArctan);
else Sub(arrayLength, aPI, aArctan)
}
Mul(arrayLength, aPI, 4);
sPI = "";
tempPI = "";
for (i = 0; i < aPI.length; i++) {
aPI[i] = String(aPI[i]);
if (aPI[i].length < cellSize && i != 0) {
while (aPI[i].length < cellSize) aPI[i] = "0" + aPI[i]
}
tempPI += aPI[i]
}
for (i = 0; i <= numDec; i++) {
if (i == 0) sPI += tempPI.charAt(i) + ".<br>";
else {
if (document.getElementById("cbCount").checked) addcount = " (" + (i) + ")";
else addcount = "";
if (document.getElementById("cbSpace").checked) thespace = " ";
else thespace = "";
if ((i) % 50 == 0 && i != 0) sPI += tempPI.charAt(i) + addcount + "<br>";
else if (i % 5 == 0) sPI += tempPI.charAt(i) + thespace;
else sPI += tempPI.charAt(i)
}
}
ans += ("PI (" + numDec + ")=" + sPI + "<br>");
ans += ("Win PI=<br>3.1415926535897932384626433832795<br>");
t2 = new Date();
timeTaken = (t2.getTime() - t1.getTime()) / 1000;
ans += "It took: " + timeTaken + " seconds";
var myDiv = document.getElementById("d1");
myDiv.innerHTML = ans
}
<form name="" onsubmit="calcPI(this.t1.value);return false;">
Number of Digits:<br>
<input type="text" name="t1" id="t1" value="100" size="25" maxlength="25">
<br>Add Count:
<input type="checkbox" name="cbCount" id="cbCount" value="" checked="checked">
<br>Add Spaces:
<input type="checkbox" name="cbSpace" id="cbSpace" value="" checked="checked">
<br>
<input type="button" value="Calculate Pi" onclick="calcPI(this.form.t1.value)">
</form>
<div id="d1"></div>
You can approximate the value of π through the use of Monte Carlo simulation. Generate a random X and Y each in the range [-1,1] Then the likelihood (X, Y) is in the unit circle centered at the origin is π/4. More samples yields a better estimate of its value. You can then estimate π by comparing the ratio of samples in the unit circle with the total number of samples and multiply by 4.
this.pi = function(count) {
var inside = 0;
for (var i = 0; i < count; i++) {
var x = random()*2-1;
var y = random()*2-1;
if ((x*x + y*y) < 1) {
inside++
}
}
return 4.0 * inside / count;
}
Here is my implementation using Infinite Series
function calculatePI(iterations = 10000){
let pi = 0;
let iterator = sequence();
for(let i = 0; i < iterations; i++){
pi += 4 / iterator.next().value;
pi -= 4 / iterator.next().value;
}
function* sequence() {
let i = 1;
while(true){
yield i;
i += 2;
}
}
return pi;
}
You can use this for your purpose
Math.PI.toFixed(n)
where n is the number of decimals you wish to display.
It displays the rounded value of pi. It can be considered fairly correct upto 15 decimal places.