How to find a first occurrence of double digit number - javascript

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");

Related

looping through split numbers javascript

I have this function, I want to loop through both of the strings and
receive a return value for compareNumber that's closest to it - that is (compareNumber +1) but only if none of it's digits are equal to any of searchNumber's digits. If any of compareNumber's digits are equal to any of searchNumber's digits, I need to fins the first value bigger than compareNumber that's not equal to any of searchNumber's digits.
function compareNumbers(searchNumber, compareNumber){
var isEqual = true;
var digitsCompare = compareNumber.toString().split('');
searchNumber.toString().split('').forEach(function(num,index) {
if(!(num===digitsCompare[index])){
isEqual = false;
}
});
return isEqual;
}
var b = compareNumbers(123,124);
console.log(b);
var d = compareNumbers(123,123);
console.log(d);
I think it would be best to consider this mathematically, as opposed to just adding 1 forever until you find a number that works.
The solution below iterates through each individual digit, increasing it by 1 until we find a digit we're allowed to use. Once we make that change, we know the rest of the digits will be replaced with the lowest number available to us.
Think of it like a combination lock, except as soon as you turn one dial, all the ones after it reset to the lowest number we're allowed to use.
function compareNumbers(n1, n2) {
var n1Array = ("" + n1).split("").map(Number);
var n2Array = ("" + n2).split("").map(Number);
var availableNumbers = [...Array(10).keys()].filter(n => !n1Array.includes(n));
//Loop through each digit in our compare string
n2Array.some((n, index) => {
let originalN = n;
//Increment it until we have a valid number
while (!availableNumbers.includes(n))
if (n < 9) n++
else {
//If we've passed 9, then we need to use the lowest number *twice*
//However, if we're changing the first number, we CAN'T replace it with a 0
n = Number((index === 0 ? availableNumbers[0] || availableNumbers[1] : availableNumbers[0]).toString() + availableNumbers[0]);
break;
}
if (originalN !== n) {
n2Array[index] = n;
var replacements = n2Array.splice(index + 1).map(n => availableNumbers[0]);
n2Array = [...n2Array, ...replacements];
return true; //Exit early
}
return false; //Keep iterating
});
//Turn [4,0,0] into 400
return Number(n2Array.join(""));
}
let result1 = compareNumbers(123,124);
console.log(result1);
let result2 = compareNumbers(123,423);
console.log(result2);
A lot of the scrappy/ugly stuff is to account for edge-cases.
The first edge-case being that if we increase a 9, then it shouldn't become a 10, but rather the lowest number available to us repeated twice.
However, there is an edge-case within that. If our lowest number available is 0, and 9 is our first number, we can't replace it with 00. Otherwise, you could end up with 915 becoming 0015.
The code is below:
function compareNumbers(searchNumber, compareNumber) {
//error check the args
var searchString = searchNumber + "";
var compareString = compareNumber + "";
if (compareString.length === 0) return "nope";
var compareInt = parseInt(compareString) + 1;
if (searchString.length === 0) {
return compareInt;
}
//don't crash the app
if (searchString.length >= 10
&& searchString.indexOf("0") >= 0 && searchString.indexOf("1") >= 0
&& searchString.indexOf("2") >= 0 && searchString.indexOf("3") >= 0
&& searchString.indexOf("4") >= 0 && searchString.indexOf("5") >= 0
&& searchString.indexOf("6") >= 0 && searchString.indexOf("7") >= 0
&& searchString.indexOf("8") >= 0 && searchString.indexOf("9") >= 0 ) {
return "nope";
}
while(containsDigits(searchString, compareInt)) {
compareInt++;
}
return compareInt;
}
function containsDigits(digits, intVal) {
var strVal = intVal + "";
var strDigits = digits + "";
for(var i = 0; i < strDigits.length; i++) {
if (strVal.indexOf(strDigits.charAt(i)) >= 0) {
return true;
}
}
return false;
}
// Examples
pairs = [[123, 124], [11, 13], [25, 35], [15, 21], [138, 546], [1, 2], [1, 1]];
pairs.forEach((pair) => console.log(`Compare [${pair[0]}, ${pair[1]}]: ${compareNumbers(pair[0], pair[1])}`));
You don't need to split a string to access its contents as an array.
var digitsCompare = compareNumber.toString();
console.log(digitsCompare.charAt(0)); <-- first char

How to "round" number, by putting zeros after the 2nd digit in javascript

I would like to "round" an integer number, by swapping all the digits after the 2nd digit to zeros. Additionally, if the number has only 1 digit, then don't do anything, and if the number has 2 digits, then swap the 2nd digit to a 0.
Example:
3 => 3
22 => 20
754 => 750
8912 => 8900
Can this be achieved without truncating the number as a string, and then rebuilding the number with zeros?
You don't need to truncate the number as a string, it can be easily achieved via mathematical calculation. Also, changing number to string and then doing any operation will be an added overhead which is not required in this case.
Refer the code below, it's quite straight forward.
Hope this helps.
function changeNumber(num){
if(Math.floor(num/10) == 0){
return num;
} else if(Math.floor(num/1000) == 0){
return Math.floor(num/10)*10;
}
else{
return Math.floor(num/100)*100
}
}
console.log(changeNumber(3));
console.log(changeNumber(22));
console.log(changeNumber(754));
console.log(changeNumber(8923));
That will work with every base-10 number.
All is about a simple math operation: number - [rest of (number / base-10 of number)]
function round(n) {
if(n < 10) return n;
var d = getTenBase(n.toString().length - 1);
return n - (n % (10 * d));
}
function getTenBase(l) {
var d = 1;
for(var i = 2; i < l; i++) {
d *= 10;
}
return d;
}
console.log(round(3));
console.log(round(22));
console.log(round(768));
console.log(round(1657));
you can just find length and first two character after that take zero with valid length and concat both
var str = '8912';
var n = str.length;
if(n == 1)
{
print(str);
} else if(n==2) {
var strFirst = str.substring(0,1);
var str2 = '0';
var res = strFirst.concat(str2);
} else if(n>2) {
var strFirst = str.substring(0,2);
var i;
var strsec ='0';
for (i = 0; i < n-3; i++) {
strsec += 0 ;
}
var res = strFirst.concat(strsec);
}
print(res);

How find the length of the longest substring?

Need find the length of the longest substring that consists of the same letter. For example, line "aaabbcaaaa" contains four substrings with the same letters "aaa", "bb","c" and "aaaa".
i found two way to do that, but all not so good;
At first way i don't make check previos similar letters here sdsffffse;
Because i check only current element and second element if(line[i] === line[i+1]).
At second way i fail when i try to check how many aa i found in that string abababaab but in object i add all a letters and length = 5;
function longRepeat(line) {
let count = {};
let letter = [];
for (let i=0; i<line.length; i++) {
count[line[i]] = i;
if(line[i] === line[i+1]){
letter.push([line[i], line[i+1]])
}
}
/*
second way
for (let x of line) {
count[x] = ~~count[x] + 1;
} */
return letter;
}
console.log(longRepeat('sdsffffse')); f = 4
console.log(longRepeat('ddvvrwwwrggg')); = 3
console.log(longRepeat('abababaab')); // last two a = 2
Possible solution:
function longestSubstr(str) {
if (!str) return 0
let maxL = 1
let curL = 1
for (let i = 0; i < str.length - 1; i++) {
let cur = str[i]
let next = str[i + 1]
if (cur === next) {
curL++
} else {
if (maxL < curL) maxL = curL
curL = 1
}
}
if (maxL < curL) maxL = curL
return maxL
}
console.log(longestSubstr("abababaab")) // 2
If you don't mind using regular expressions.
function func(line) {
let reg = /(\w)\1+/g;
let longest = line.match(reg).sort((a, b) => {
a.length - b.length
}).pop();
console.log(line + ' : ' + longest);
}
func('ddvvrwwwrggg');
func('sdsffffse');
func('abababaab');
func('aaabbcaaaa');
func('aaaasdfbbbbyyyweryyyuurweuuuuuu');
/(\w)\1+/g will match a sequence of the same character, using the match() method we get all the sequences, sort them by length, and get the last item in the array, i didn't know what to do in case of equal length, so i'll leave that you, i'm merely presenting an idea, and it's for you to improve it :)
#python
def long_repeat(line):
line = line.lower()
max = 1
if len(line) == 0:
return 0
for i in range(0, len(line) - 1):
count = 1
while line[i] == line[i + 1]:
count += 1
if max < count:
max = count
if i < len(line) - 2:
i += 1
else:
break
return max

Javascript Integer Array Error

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;
}
}

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