Javascript Integer Array Error - javascript

I'm making a function that takes in user input and must display it as 7 characters i.e. if 42.54 was entered it would display 0004254. My issue is that I'm taking an integer and applying it to an array causing an undefined error when applying the 0's
function BackDataDefaultInput() {
// Balance
var count;
var newNum = "";
var balanceText = document.getElementById('balanceNumBox').value;
count = balanceText.length;
while (count > 0 && count < 7) {
newNum += '0';
count++
}
var formattedBalance = parseInt(balanceText, 10) * 100;
for (var i = 0; i < balanceText.length; i++) {
formattedBalance[i] = new Array();
// Error here showing as undefined for formattedBalance[i]
newNum += formattedBalance[i];
}
This code worked before I had to multiply it by 100 to get the right format. as I was just appending two strings. Can somebody help me think of a solution?

Primitives (like numbers) are immutable; if you have
var formattedBalance = parseInt(balanceText, 10) * 100;
you can't proceed to reassign index properties like
formattedBalance[i] = new Array();
It would probably be easier to remove the (possible) period with a regex and use padStart rather than mess with arrays:
function BackDataDefaultInput() {
const balanceText = '42.54'; // document.getElementById('balanceNumBox').value;
console.log(
balanceText
.replace(/\./g, '')
.padStart(7, '0')
);
}
BackDataDefaultInput();

Try to use following function.
var balanceText = "42.54"; //document.getElementById('balanceNumBox').value;
var formattedBalance = balanceText * 100;
function formatInteger(str, max) {
str = str.toString();
return str.length < max ? formatInteger("0" + str, max) : str;
}
console.log(formatInteger(formattedBalance, 7));

Answer to my question in case it helps anyone that comes across this page:
function BackDataDefaultInput() {
var balanceText = document.getElementById('balanceNumBox').value;
var balance = parseFloat(balanceText) * 100;
balanceText = String(balance);
while (balanceText.length > 0 && balanceText.length < 7) {
balanceText = '0' + balanceText;
}
}

Related

How to find a first occurrence of double digit number

So, I am pushing elements into array through prompt until getting 0. After that I am trying to find the first double digit number. For example if the array is [2,3,55,0] my program should return 55.
function findFirstDouble() {
var niz = []
var a = 1;
for (var i = 1; a != 0; i++) {
var unos = parseInt(prompt("Enter number :"))
niz.push(unos)
a = unos
}
alert(niz);
for (var i = 0; i < niz.length; i++) {
if (niz[i] / 10 > 0 && niz[i] / 100 == 0) {
console.log(niz[i]);
break;
}
else {
alert("No double digit numbers!")
break;
}
}
}
findFirstDouble();
Please use built in js function find.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Here is the solution
// I assume that you already have an array
const niz = [2,3,55,0]
const firstDoubleDigit = niz.find(num => num < 100 && num >= 10)
console.log(firstDoubleDigit)
Here is the answer I think you are looking for.
I omitted the array filling part.
Why would you do any kind of division if you just need to check every number and if the first one matches the criteria then you've got your double digit number hence exit the loop with break or return keyword.
var niz = [1, 2, 55, 13];
for (var i = 0; i < niz.length; i++) {
if (niz[i] > 9 && niz[i] < 100) {
console.log('Pronadeni broj je:', niz[i]);
break;
}
}
You can also convert to string: if (niz[i].toString().length===2){ // your number }
Easy way without math is just to convert it to a string.
const data = [2,3,55,0];
const res = data.findIndex(n=>`${n}`.length===2);
console.log(res > -1 ? "Exists at position " + res : "Doesn't exist");
Mathematically:
const data = [2,111,3,55,0];
const res = data.find(n=>n<100&&n>9);
console.log(res ? "Exists " + res : "Doesn't exist");

My code crashes javascript console

My code is freezing Chrome (and Firefox), won't execute on Coderbyte console but when I submit the code as an answer to the exercise, it does take.
var numOrdered = 0;
var numReversed = 0;
var tries = 0;
function KaprekarsConstant(num) {
var arr = [];
while (num > 0) {
arr.unshift(num % 10);
num = num / 10 | 0;
}
arr.sort();
numOrdered = Number(arr.join(''));
numReversed = Number(arr.reverse().join(''));
while (num !== 6174) {
num = numReversed - numOrdered;
tries += 1;
}
return tries;
};
KaprekarsConstant(8593);
Why is it crashing? How can I prevent it?
Thank you guys!
the actual problem is the second while loop:
while (num !== 6174) {
num = numReversed - numOrdered;
tries += 1;
}
Removing it, your code doesn't hang the browser:
var numOrdered = 0;
var numReversed = 0;
var tries = 0;
function KaprekarsConstant(num) {
var arr = [];
while (num > 0) {
arr.unshift(num % 10);
num = num / 10 | 0;
}
arr.sort();
numOrdered = Number(arr.join(''));
numReversed = Number(arr.reverse().join(''));
return tries;
};
console.log(KaprekarsConstant(8593));
You need to revisit the logic in the second loop so that it doesn't become infinite.
The second loop makes your code to hang up.Try this. I have made some changes.
var numOrdered = 0;
var numReversed = 0;
var tries = 0;
function KaprekarsConstant(num) {
while (num !== 6174) {
var arr = [];
while(num >0){
arr.unshift(num % 10);
num = num / 10 | 0;
}
arr.sort();
numOrdered = Number(arr.join(''));
numReversed = Number(arr.reverse().join(''));
num = numReversed - numOrdered;
tries += 1;
}
return tries;
};
KaprekarsConstant(8593);
The while loop in the post keeps calculating the same value for num, so it it is not immediately 6174, the loop continues forever.
Basically the code is not following the algorithm for demonstrating Kaprekar's constant as shown on Wikipedia:
pad numbers of less than 4 digits with leading zeroes,
subtract the smaller number from the larger of { number, number with reversed digits), and
repeat from the step of extracting digits from the latest subtraction result.
Spoiler alert - here's a working example of a recursive function with the extra pieces of logic:
"use strict";
function KaprekarsConstant(num, tries=0) {
if( num == 6174) // Kaprekar's constant.
return tries;
if( num == 0) // degenerate case, digits are the same
return -tries;
var arr = [];
while (num > 0) {
arr.unshift(num % 10);
num = num / 10 | 0;
}
while( arr.length<4) { // leading zeroes as required
arr.unshift(0);
}
arr.sort();
var numOrdered = Number(arr.join(''));
var numReversed = Number(arr.reverse().join(''));
num = Math.abs( numOrdered - numReversed) // larger - smaller
return KaprekarsConstant( num, ++tries); // try again
};
// and test
function test() {
var num = Number(input.value);
if( Number.isNaN(num) || num < 1 || num > 9999) {
throw new Error("Enter number between 1 and 9999");
}
console.log("Tries = %s", KaprekarsConstant(num) );
}
<label> Enter 1 to 4 digit number: <input type="text" id="input"></label><br>
<button type="button" onclick="test()">Calculate tries</button>
While the answers do address your question, the solutions and the code are missing the part about leading zeros as in wiki Kaprekar's constant
and the whole solution is very simple
function KaprekarsConstant(num)
{
var tries=0;
var numOrdered =0;
var numRevesed=0;
while(num!=6174)
{
numOrdered=("0000" + num).substr(-4,4).split("").sort().join("");
numRevesed=numOrdered.split("").reverse().join("");
num = numRevesed-numOrdered;
tries+=1;
}
return tries;
}
KaprekarsConstant(8593);
To the reason for 'Why is it crashing?', its maybe due to Infinite Loop .
The response I got when I try to run your code
Possible infinite loop detected.
Error: Infinite loop
at KaprekarsConstant (script 19:68)
at script 27:1
Thank you everybody for the answers!!
Thanks to #Jaromanda X I realise the last while loop was infinite, since
num = numOrdered - numReversed;
will always be the same.
I realised I had to re-arrange the numbers every time so I create a function for that and incorporate it into the while loop.
I also added a bit of code from #traktor53 to add the leading zeros in case of a number with less than 4 digits.
And to finish I declare
var tries = 0;
inside the function so it will start from zero in each run.
.
.
Final result:
var numOrdered = 0;
var numReversed = 0;
function KaprekarsConstant(num) {
var tries = 0;
function order(num) { // function to order the numbers
var arr = [];
while (num > 0) {
arr.unshift(num % 10);
num = num / 10 | 0;
}
while(arr.length<4) { // leading zeroes as required
arr.unshift(0);
}
arr.sort();
numOrdered = Number(arr.join(''));
numReversed = Number(arr.reverse().join(''));
}
while (num !== 6174) {
order(num);
num = Math.abs(numOrdered - numReversed); // larger - smaller
tries += 1;
}
return tries;
};
KaprekarsConstant(8593);

How to split numbers into individual

I have this whole number 75892. i want to split it in individual and then add below is my code. it works fine but is there any other solution to minimize my code? thanks
var x=75892;
var d,ans=0;
while(x!=0){
d=x%10;
ans=ans+d;
x=parseInt(x/10);
}
document.write("SUM:"+ans);
That approach is fine other than the parseInt part. parseInt will first convert the number to string, then parse that string. You wanted Math.floor:
x = Math.floor(x / 10);
You can also use += and just generally there are a couple of shortcuts you could take:
var x = 75892;
var ans = 0;
while (x != 0) {
ans += x % 10;
x = Math.floor(x / 10);
}
document.write("SUM:" + ans);
Another approach would be to go through the digits, e.g. a string-based approach instead of a math-based one. But frankly, I don't think it would be better.
You wanted shorter - here's a one-line ES6 version:
var ans = [...(String(x))].map(Number).reduce((p, c) => p + c);
Use spread on a stringified version of x, convert them to numbers, then use reduce to sum the numbers.
DEMO
var x="" + 75892;
var sum = 0;
for( var i = 0; i < x.length; i++ )
{
sum += parseInt( x[i] );
}
console.log( "sum: " + sum );
Please try this once.
Use, please review Sum of a string of one-digit numbers in javascript?
var sum = function(a,b){return a+b}
function stringSum(s) {
var int = function(x){return parseInt(x,10)}
return s.split('').map(int).reduce(sum);
}
document.write(stringSum("75892"))
You just need to split the variable-
var x=75892;
var arr = x.split('');
var count=0;
for (var i=arr.length; i--;) {
count = count+parseInt(arr[i]);
}
The following code is, when i was thought in college days, Now share with you. Beauty is there is no loop.
var x=75892;
var d,ans = 0;
x = parseInt(x);
if(x < 0){
x = -1 * x;
}
if(x > 0){
d = x % 9;
if(d == 0){
ans = 9;
}else{
ans = d;
}
}
document.write("SUM:"+ans);
If you're asking if there's a smarter way, than just peeling off digits at the end, then no - not in the decimal system at least.
Unless you want to reduce to a single digit (eg. 75892 -> 31 -> 4) in which case
function(d){
if(d === 0){
return 0;
}
var m = d%9;
return m === 0 ? 9 : m;
}
will do the trick

Using Modulus to loop through

I've been stuck on this last part of my assignment for the longest time. I'm trying to loop through the alphabet using modulus. delta is the number of letters you have to move forward or backwards to get the real letter. SO if given getchars("H",-2), the function is supposed to return F. A problem arises however if the chars.charAt(chars.getIndexOf(data.charAt(i))) ever equals a number less than 0. I want to be able to give my function ("A", -1) or any negative number and have it return "Z".
This is an assignment for class so if possible please keep it to just modulus. I've been working on this last part for like 2 hours now.
function getChars(data,delta)
{
var chars;
var i;
var foundAt;
var newString;
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
data = data.toUpperCase();
delta = Math.min(chars.length, delta);
i = 0;
newString = "";
while (i < data.length)
{
if(delta <= 0)
{
foundAt = (chars.indexOf(data.charAt(i)) + delta) ;window.alert(foundAt)
//newString = newString + chars.charAt(foundAt);
//i = i + 1;
}
else if((chars.indexOf(data.charAt(i)) < 0))
{
foundAt = data.charAt(i);
newString = newString + foundAt;
i = i + 1;
}
else
{
foundAt = ((chars.indexOf(data.charAt(0 + i)) + delta)) % chars.length;window.alert(foundAt);
newString = newString + chars.charAt(foundAt);window.alert(newString);
i = i + 1;
}
}
//return newString;
}
To be flexible, you can use i = chars.length - 1; and first after that do the found at.
You have to use you own modulus function :
function modulus(n,m) {
return ((n%m)+m)%m;
};
With your following code :
function getChars(data,delta)
{
var chars;
var i;
var foundAt;
var newString;
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
data = data.toUpperCase();
i = 0;
newString = "";
while (i < data.length)
{
newString += chars.charAt(modulus(chars.indexOf(data[i])+delta,26))
i++;
}
return newString;
}

Get Number of Decimal Places with Javascript

How would I calculate the number of decimal places (not digits) of a real number with Javascript?
function countDecimals(number) {
}
For example, given 245.395, it should return 3.
Like this:
var val = 37.435345;
var countDecimals = function(value) {
let text = value.toString()
// verify if number 0.000005 is represented as "5e-6"
if (text.indexOf('e-') > -1) {
let [base, trail] = text.split('e-');
let deg = parseInt(trail, 10);
return deg;
}
// count decimals for number in representation like "0.123456"
if (Math.floor(value) !== value) {
return value.toString().split(".")[1].length || 0;
}
return 0;
}
countDecimals(val);
The main idea is to convert a number to string and get the index of "."
var x = 13.251256;
var text = x.toString();
var index = text.indexOf(".");
alert(text.length - index - 1);
Here is a method that does not rely on converting anything to string:
function getDecimalPlaces(x,watchdog)
{
x = Math.abs(x);
watchdog = watchdog || 20;
var i = 0;
while (x % 1 > 0 && i < watchdog)
{
i++;
x = x*10;
}
return i;
}
Note that the count will not go beyond watchdog value (defaults to 20).
I tried some of the solutions in this thread but I have decided to build on them as I encountered some limitations. The version below can handle: string, double and whole integer input, it also ignores any insignificant zeros as was required for my application. Therefore 0.010000 would be counted as 2 decimal places. This is limited to 15 decimal places.
function countDecimals(decimal)
{
var num = parseFloat(decimal); // First convert to number to check if whole
if(Number.isInteger(num) === true)
{
return 0;
}
var text = num.toString(); // Convert back to string and check for "1e-8" numbers
if(text.indexOf('e-') > -1)
{
var [base, trail] = text.split('e-');
var deg = parseInt(trail, 10);
return deg;
}
else
{
var index = text.indexOf(".");
return text.length - index - 1; // Otherwise use simple string function to count
}
}
You can use a simple function that splits on the decimal place (if there is one) and counts the digits after that. Since the decimal place can be represented by '.' or ',' (or maybe some other character), you can test for that and use the appropriate one:
function countPlaces(num) {
var sep = String(23.32).match(/\D/)[0];
var b = String(num).split(sep);
return b[1]? b[1].length : 0;
}
console.log(countPlaces(2.343)); // 3
console.log(countPlaces(2.3)); // 1
console.log(countPlaces(343.0)); // 0
console.log(countPlaces(343)); // 0
Based on Gosha_Fighten's solution, for compatibility with integers:
function countPlaces(num) {
var text = num.toString();
var index = text.indexOf(".");
return index == -1 ? 0 : (text.length - index - 1);
}
based on LePatay's solution, also take care of the Scientific notation (ex: 3.7e-7) and with es6 syntax:
function countDecimals(num) {
let text = num.toString()
if (text.indexOf('e-') > -1) {
let [base, trail] = text.split('e-')
let elen = parseInt(trail, 10)
let idx = base.indexOf(".")
return idx == -1 ? 0 + elen : (base.length - idx - 1) + elen
}
let index = text.indexOf(".")
return index == -1 ? 0 : (text.length - index - 1)
}
var value = 888;
var valueLength = value.toString().length;

Categories

Resources