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

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

Related

JavaScript Math Function

Given an object containing the number of positive and negative reviews, for example { positive: 24, negative: 8 }, return the review positivity score.
function getReviewPositivityScore (positive, negative) {
let a = positive;
let b = negative;
let result = a - b ;
return result;
}
module.exports = getReviewPositivityScore;
Error message I get:
getReviewPositivityScore
1) should return the number of positive reviews minus the number of negative reviews
0 passing (6ms)
1 failing
getReviewPositivityScore
should return the number of positive reviews minus the number of negative reviews:
AssertionError: expected NaN to deeply equal 16
expected - actual
-NaN
+16
at Context. (.guides/secure/test3.5.1.js:8:17)
at processImmediate (internal/timers.js:439:21)
Since you are passing an object you only need one parameter as function input, and then access the values from it:
function getReviewPositivityScore (object) {
return object.positive - object.negative;
}

JavaScript function receives two strings and returns n

I've been trying to complete this challenge recently but with no success, tried many ways but
for some reason I don't manage to complete all the examples below.
I will be appreciated if someone can assist me with that, showing me step by step.
Write a function that receives two strings and returns n, where n is
equal to the number of characters we should shift the first string
forward to match the second. For instance, take the strings "fatigue"
and "tiguefa". In this case, the first string has been rotated 5
characters forward to produce the second string, so 5 would be
returned.
If the second string isn't a valid rotation of the first string, the
method returns -1. Specification shiftedDiff(first, second) provide
amount of rotations to match words
Parameters first: String - word to be matched
second: String - word to be checked
Return Value Number - Number of rotations, nil or -1 if invalid
Examples:
"coffee", "eecoff" => 2
"eecoff", "coffee" => 4
"moose", "Moose" => -1
"isn't", "'tisn" => 2
"Esham", "Esham" => 0
"dog", "god" => -1
function shiftedDiff(first, second) {
// Split the second word into an array for
// easier manipulation
const arr = [...second];
// Iterate over the array
for (let i = 0; i < arr.length; i++) {
// If the first and joined array match
// return the index
if (first === arr.join('')) return i;
// Otherwise `shift` off the first element of `arr`
// and `push` it on the end of the array
arr.push(arr.shift());
}
// If there are no matches return -1
return -1;
}
console.log(shiftedDiff('coffee', 'eecoff')); // 2
console.log(shiftedDiff('eecoff', 'coffee')); // 4
console.log(shiftedDiff('moose', 'Moose')); // -1
console.log(shiftedDiff("isn't", "'tisn")); // 2
console.log(shiftedDiff('Esham', 'Esham')); // 0
console.log(shiftedDiff('dog', 'god')); // -1
Documentation
push
shift
Spread syntax
let shiftedDiff = (f, s) => {
let r = -1;
f.split('').forEach((e, i) => {
f = f.substr(1) + e;
if (f == s) r = f.length - (i + 1)
})
return r;
}
console.log(shiftedDiff("coffee", "eecoff"))
console.log(shiftedDiff("eecoff", "coffee"))
console.log(shiftedDiff("moose", "Moose"))
console.log(shiftedDiff("isn't", "'tisn"))
console.log(shiftedDiff("Esham", "Esham"))
console.log(shiftedDiff("dog", "god"))

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.

An algorithm to check if a number is an Extra Perfect Number (it has the same first and last bits) in javascript

This may seem obvious, but what is exactly is an extra perfect number? I need to write an algorithm to find extra perfect for a given n, from 1 thru n. Unfortunately, I can't seem to wrap my mind around the question's wording. These are the examples given:
extraPerfect(3) ==> return {1,3}
extraPerfect(7) ==> return {1,3,5,7}
Task:
Given a positive integer N, return the extra perfect numbers in range from 1 to N.
A number is called Extra Perfect Number if it has the same first and last bits (set bits).
Notes:
Only positive integers will be passed.
The returned vector/list should contain the extra perfect numbers in
ascending order (from lowest to highest).
Example #1
extraPerfect(3) ==> return {1,3}
Explanation:
(1)10 = (1)2
First and last bits as set bits.
(3)10 = (11)2
First and last bits as set bits.
Example #2
extraPerfect(7) ==> return {1,3,5,7}
Explanation:
(5)10 = (101)2
First and last bits as set bits.
(7)10 = (111)2
First and last bits as set bits.
It seems to me that an extra perfect number is simply an odd number as, in base 2, it will always start and end with a 1, whereas an even number will always start with a 1 but end with a 0.
Ah now I see I was wrong because I thought it is all about palindroms. However I hope it can be still helpful. That's the code for palindroms in section between 1 to prompt's value.
var exns = (function(){
function dec2bin(dec){
return (dec >>> 0).toString(2);
}
function isEXN(num){
var con = dec2bin(num); // 11011 = 3 + 24 = 27
var accurate = Math.ceil(con.length/2); // 5/2 = 3
var lenmin = con.length-1;
for(var i = 0; i < accurate; i++){
if(con.charAt(i) !== con.charAt(lenmin-i))
return false;
}
return true;
}
var max = parseInt(prompt("Numbers from 1 to ...?"));
var exns = [];
if(!isNaN(max)){
for(var i = 1; i<=max; i++){
if(isEXN(i))
exns.push(i);
}
}
return exns;
})();
Exns should contain array with values.
It looks like extraPerfect should return a list of all numbers less than the argument which have the same first and last digit after converting the decimal argument to binary.
For example:
Decimal - Binary
1 - 1
2 - 10
3 - 11
4 - 100
5 - 101
6 - 110
7 - 111
You'll notice the bold values have the same first and last binary digits.
Some pseudo-code might look like:
function extraPerfect( n ){
var perfects = [];
for(i=0; i<n; i++){
var binary = toBinary(i);
if(binary[0] === binary[binary.length]){
perfects.push(i);
}
}
return perfects;
}
You could pull an algorithm form the pseudo-code.
A Perfect Number is equal to the sum of its positive divisors.
function perfect(num){
for(var i=1,n=0; i<num; i++){
if(num % i === 0){
n += i;
}
}
return n === num;
}
console.log(perfect(6));
console.log(perfect(7));
console.log(perfect(28));
console.log(perfect(8127));
console.log(perfect(8128));

How to get a term before a character?

How to get the number before 'x'?
I tried using .split('x')[0] but it grabs everything before 'x'.
123x // Gives 123
123y+123x - // Gives 123
123x+123x - // Gives 246
I've tested a function which uses regex that I think will work. I've included the results, an explanation of how the function works, and then a commented version of the function.
Note, this doesn't handle any algebra more complex than adding and subtracting simple terms. I would refer to https://newton.now.sh/ for that, it's an API which can handle simplification (I am not affiliated).
Results:
console.log(coefficient("-x+23x")); // 22
console.log(coefficient("123y+123x")); // 123
// replaces spaces
console.log(coefficient("x + 123x")); // 124
console.log(coefficient("-x - 123x")); // -124
console.log(coefficient("1234x-23x")); // 1211
// doesn't account for other letters
console.log(coefficient("-23yx")); // 1
Explanation:
First the function removes spaces. Then it uses a regex, which finds any sequence of numbers that are followed by an 'x'. If there's a +/- in front, the regex keeps that. The function loops through these sequences of numbers, and adds them to a total. If there's an 'x' that does not have numbers with it, its coefficient is assumed as -1 or 1.
Commented Code:
function coefficient(str) {
// remove spaces
str = str.replace(/\s/g, '');
// all powerful regex
var regexp = /(\+|-)?[0-9]*x/g
// total
sum = 0;
// find the occurrences of x
var found = true;
while (found) {
match = regexp.exec(str);
if (match == null) {
found = false;
} else {
// treated as +/- 1 if no proceeding number
if (isNaN(parseInt(match[0]))) {
if (match[0].charAt(0) == "-") {
sum--;
} else {
sum++;
}
// parse the proceeding number
} else {
sum += parseInt(match[0]);
}
}
}
return sum;
}
I don't know if there is sufficient cleverness in ECMAScript regular expressions to do look behind, but you can do it with match and post processing to remove the "x".
If the intention is to sum the terms, then a further operation with reduce is required. Trimming the x could be combined with reduce so that map isn't required.
console.log(
'123x+123x'.match(/\d+x/ig).map(function(v){
return v.slice(0,-1)
}).reduce(function(sum, v){return sum + +v},0)
);
console.log(match('123x+123y+456x', 'x'))
console.log(match('123x+123y+456x', 'y'))
function match(str, x) {
return str.match(new RegExp('\\d+' + x, 'g')).reduce((cur, p) => {
return cur + parseInt(p.substr(0, p.length - x.length))
}, 0)
}

Categories

Resources