Find the Last Index of a Non-Zero Digit using Javascript - javascript

How can you find the last occurrence of a non-zero digit in a number/string in Javascript? With that, we will be able to split a zero-padded number into the actual number and its zero padding. Any JS/Node library can be used.
Tried using .lastIndexOf() but didn't find a way to define a non-zero digit.
Input
1.23400
1.00050
1.03456
Output
['1.234', '00']
['1.0005', '0']
['1.03456']

Use a regex :
/^([0-9]+\.?[0-9]*?)(0*)$/
/^([0-9]+\.?[0-9]*?)(0*)$/.exec('1.23400'); // return ["1.23400", "1.234", "00"]
/^([0-9]+\.?[0-9]*?)(0*)$/.exec('1.03456'); // return ["1.03456", "1.03456", ""]
You can use the parseFloat too if you juste interest by getting the significative part of the number.
parseFloat('1.23400') // return 1.234

Try this :
'1.23400'.match(/^.*?(?=0*$)|0+$/g)
// ^.*?(?=0*$) : everything before zero or more trailing zeros
// 0+$ : one or more trailing zeros

Try this:
function lastIndexOfDigit(str) {
var last_indices = [];
[1, 2, 3, 4, 5, 6, 7, 8, 9].map(function (digit) {
last_indices.push(str.lastIndexOf(digit));
});
var indices = last_indices.sort(function (a, b) {
return a - b;
});
return indices[indices.length - 1];
}

Related

JS - How to calculate all possible +, -, ÷, × math operation for 4 specific numbers?

Let's say I have these four numbers: [1, 5, 3, 8].
And I want to check which of the math operations equals to 10. Also the order of the numbers matters, meaning the first number should always be the first index in the array and so on.
For example:
(1 + 5) ÷ 3 + 8
1 x 5 - 3 + 8
How can I achieve this?
Honestly, I have no idea how I should approach this. So any help would be greatly appreciated.
We create an Expr class to represent expressions, which consist of two operands (which may be simple numbers or other expressions) and an operator. This provides convenience functions for evaluating the expression and outputting the expression as a string.
In the simple case, where there are only two expressions x and y, we return all possible combinations x+y, x-y, x*y, x÷y.
Then, when there are more expression operands, we find (all combinations of (x operator y) with ...z), and (x operator (all combinations of y with ...z))
class Op {
constructor(symbol,func) { this.symbol = symbol; this.func = func; }
invoke(x,y) { return this.func(
x instanceof Expr ? x.eval() : x,
y instanceof Expr ? y.eval() : y)
}
toString() { return this.symbol }
}
const ops = [
new Op('+', (x,y)=>x+y), new Op('-', (x,y)=>x-y),
new Op('*', (x,y)=>x*y), new Op('÷', (x,y)=>x/y),
]
class Expr {
constructor(x,op,y){ this.x=x; this.op=op; this.y=y }
eval() { return this.op.invoke(this.x, this.y) }
toString() { return `(${this.x}${this.op}${this.y})` }
}
const f = (x,y,...z) =>
!z.length ? ops.map(op=>new Expr(x,op,y)) :
[...f(x,y).flatMap(expr=>f(expr, ...z)),
...f(y,...z).flatMap(expr=>f(x, expr))]
// show all combinations
console.log(f(...[1, 5, 3, 8]).map(i=>i.toString()))
// show only combinations that evaluate to 10
console.log(f(...[1, 5, 3, 8]).filter(i=>i.eval()===10).map(i=>i.toString()))
Construct the set of possible results for each contiguous range of the input values.
If a range has a single number, then the only mathematical expression constructible is the number itself.
Otherwise, if you have a range a[i], a[i+1], ..., a[j] then for each k from i+1 to j, find the set of possible results constructible from a[i], a[i+1], ..., a[k-1], and the set of possible results constructible from a[k], a[k+1], ..., a[j], then combine them using +, -, * and / in every possible combination.
For example, for [1, 5, 3, 8] there's three ways of breaking up the sequence:
[1] [5, 3, 8]
[1, 5], [3, 8]
[1, 5, 3], [8]
Working through just the second line: [1, 5] can produce {1+5, 1-5, 1*5, 1/5} and [3, 8] can produce {3+8, 3-8, 3*8, 3/8}, so this gives {(1+5)+(3+8), (1+5)-(3+8), (1+5)*(3+8), (1+5)/(3+8), (1-5)+(3+8), (1-5)-(3+8), ..., (1/5)+(3/8), (1/5)-(3/8), (1/5)*(3/8), (1/5)/(3/8)}.
This is workable as-is if you only have 4 input numbers, but if you have more then you will find you can memoize or use dynamic programming to avoid computing the same things repeatedly. It will always be exponential time though, since the range of constructible values grows exponentially.

How to remove the numbers that already occur with their digits reversed

I need a function that will take an array of numbers, and which will return an array that only retains the numbers that are unique in their digit sequence, i.e. that only occur once even if you would reverse their digits.
This is my code so far:
var a=[5,8,3,8,3,7,5,12,21];
console.log(a);
let output=[...new Set([...a])] // it removes the repeated data...
console.log(output);
This works for the numbers 3, 8 and 5, whose duplicates are removed, but the value 21 should also be removed, because there is already 12, which is 21 with the digits in reversed order.
How can I achieve that?
The expected output for the above example is:
[5,8,3,7,12]
My code returns:
[5,8,3,7,12,21]
You need (of course) to include the logic of reversing digits in a number.
I will assume that when the rightmost digit of a number is 0, that the reversal of that number is not defined. So the reversal of 19 is 91, but the reversal of 190 is not 91, but undefined (or NaN).
First define a function for that reversal of digits, and then use the idea of building a set:
function reverseDigits(num) {
// A Number should not have 0 as first digit
// unless it is 0
if (num && num % 10 == 0) return NaN;
return +[...String(num)].reverse().join("");
}
function specialUnique(a) {
const set = new Set;
for (const value of a) {
if (!set.has(value) && !set.has(reverseDigits(value))) {
set.add(value);
}
}
return [...set];
}
// Example input
const a = [5,8,3,8,3,7,5,12,21];
const output = specialUnique(a);
console.log(output);
You can use the filter.
let valueToRemove = 21;
output = output.filter((item) => item !== valueToRemove);

Square every digit of a number

I am trying to learn JavaScript but find it to be a bit confusing. I am trying to square every digit of a number
For example: run 9119 through the function, 811181 will come out, because 9^2 is 81 and 1^2 is 1.
My code:
function squareDigits(num){
return Math.pow(num[0],2) && Math.pow(num[1],2);
}
Correct code:
function squareDigits(num){
return Number(('' + num).split('').map(function (val) { return val * val;}).join(''));
}
I do not know why .map, .split, and .join was used to answer the question.
.split takes a string and splits it into an array based on the character(s) passed to it '' in this case.
So
("9119").split('') === ["9", "1", "1", "9"]
.map works like a for loop but takes a function as an argument. That function is applied to every member of the array.
So
["9", "1", "1", "9"].map(function(val) { return val * val;}) === ["81", "1", "1", "81"]
.join does the opposite of .split. It takes an Array and concatenates it into a string based on the character(s) passed to it.
So
["81", "1", "1", "81"].join('') === "811181"
Additionally, the && operator checks to see if the expressions on either side of it evaluate to true. If both expressions evaluate to true, only then will it return true. It always returns a Boolean though. I think you wanted to convert your values to string first using Number.toString() and then append them together using the + operator
return Math.pow(num[0],2).toString() + Math.pow(num[1],2).toString();
function squareDigits(num) {
// Convert the result to a number. "252525" -> 252525
return Number(
num.toString() // num === "555"
.split('') // ["5", "5", "5"]
.map(elem => elem * elem) "5" * "5" === 25 (Type coversion)
// Now we have [25, 25, 25]
.join('') // "252525"
);
}
squareDigits(555);
There are several methods of this, but the first that comes to mind is to pass the number as a string, split it, then parse the numbers, square them individually, make them strings, and paste them back together, it sounds complex but makes sense once you see it
//function takes number as an argument
function convertNumber(num){
//the toString method converts a number into a string
var number = num.toString();
//the split method splits the string into individual numbers
var arr = number.split("");
//this variable will hold the numbers that we square later
var squaredArr = [];
//the for loop iterates through everything in our array
for(var i=0; i<arr.length; i++){
//parseInt turns a string into a number
var int = parseInt(arr[i]);
//Math.pow raises integers to a given exponent, in this case 2
int = Math.pow(int, 2);
//we push the number we just made into our squared array as a string
squaredArr.push(int.toString());
}
//the function returns the numbers in the squared array after joining
//them together. You could also parseInt the array if you wanted, doing
//this as parseInt(squaredArr[0]); (this would be done after joining)
return squaredArr.join('');
}
Basically you need single digits for getting squared values.
You could take Array.from, which splits a string (which is a type with an implemented Symbol.iterator) into characters and uses an optional maping for the values.
function sqare(number) {
return +Array.from(number.toString(), v => v * v).join('');
}
console.log(sqare(9119));
try these code..
function squareDigits(n) {
return +(n.toString().split('').map(val => val * val).join(''));
}
console.log(squareDigits(4444));
here + sign is convert the string into an integer.

How to identify any string?

An array shows 3 numbers randomly, and I had to write a code that sums the 3 numbers, but the array has a trick to sometimes show a string:
[96, ".!asd", 182]
["##$%", 5, 43]
[64, "bd", 48]
I would like to use an "if" that would return "not valid" if there's a string in the array.
if (...){
return not valid
}
Please, if there's a way to identify any string, could you tell me the code?
You can use Array.prototype.some() to see if your array contains NaN's
var x = [96, ".!asd", 182]
var y = [96, 1000, 182]
console.log(x.some(isNaN))
console.log(y.some(isNaN))
You should use the isNaN function as it is explained here : Is there a (built-in) way in JavaScript to check if a string is a valid number?
isNaN(123) // false
isNaN('123') // false
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true
isNaN('10px') // true
You can use isNaN to determine if a stirng is a number
isNaN('123') //false
isNaN('Hello') //true
Use the object Number:
if (Number.isNaN(+element_in_array)) return "Not Valid!!"
function sum(array) {
if (array.some((n) => Number.isNaN(+n))) {
return "Invalid data, at least one element is not a number.";
}
return array.reduce((a, n) => a + Number(n), 0);
}
console.log(sum([96, ".!asd", 182]))
console.log(sum(["##$%", 5, 43]))
console.log(sum([64, "bd", 48]))
console.log(sum([64, 44, 48]))
You could use NaN to determine if all elements are numbers by using an unary plus to convert the string to number. If succeed, you get a number for summing, if not then NaN is returned and summed. A single NaN spoils the result and the result is NaN.
function not(fn) {
return function (v) {
return !fn(v);
};
}
function sum(array) {
return array.reduce((a, b) => +a + +b);
}
console.log([[96, ".!asd", 182], ["##$%", 5, 43], [64, "bd", 48], [2, 3, 5]].map(sum).filter(not(isNaN)));
try using typeof to validate wether or not you are dealing with a string.mdn typeof
You can use if type(x) == str to check if a variable x is of type String. It is a built-in function. Please refer to official python documentation to know more.
https://docs.python.org/3/library/functions.html#type

Make choice from array semi-randomly based on string

I have this problem. I'd like to make random a choice from array [1,2,3,4] based on arbitrary 6 letter string in such way that this choice is always same if string is same.
So if i have string 'dogdog' function would return always '3' for example, but '4' for 'bigcat' etc.
I think the solution might be first hashing the string. How could one convert hash string into choice from array?
You can calculate a hash from a string and take the array item at [hash % array.length]. An example with the DJB hashfunc (see http://www.cse.yorku.ca/~oz/hash.html for more):
function djbHash(s) {
let hash = 5381;
for (let c of s) {
hash = hash * 33 + c.charCodeAt(0);
}
return hash;
}
function mapToValues(s, values) {
return values[djbHash(s) % values.length];
}
console.log(mapToValues('dogdog', [1, 2, 3, 4]));
console.log(mapToValues('bigcat', [1, 2, 3, 4]));
A really simple hash function:
Change each letter of your word by a number (a is 1, b is 2, etc.). Let's call w the whole word changed in a number.
Calculate i = w mod 4. i will be a number between 0 and 3. Add 1 to it.
Congrats, you can now associate any word to a "random" number between 1 and 4. You can of course replace 4 by any other number to associate each world to a random number in any range.

Categories

Resources