I am trying to find a solution for this:
Users are asked to type in a random set of numbers sequentially:
var num1 = prompt("Enter 1st set of numbers");
var num2 = prompt("Enter 2nd set of numbers");
var num3 = prompt("Enter 3rd set of numbers");
var myNumbers =[num1, num2, num3];
Now I am trying to take compare the sum of the digits in each element of the array. For instance, if myNumbers[0] = 32, myNumber[1] = 45, what's the function to compare 5 (3+2) and 9 (4+5)?
I am trying to compare the sum of each elements by adding the numbers in that element, and return the largest number. So if num1= 1234, then the sum of myNumbers[0] should be 10. By comparing , if num2 = 3456, then the sum should be 18, the function should return num2.
var num1 = prompt("Enter 1st set of numbers");
var num2 = prompt("Enter 2nd set of numbers");
var num3 = prompt("Enter 3rd set of numbers");
// finds the sum of your array, parsing each element as an integer
var sum = function(array){
var digits = array.split("")
return digits.reduce(function(a, b) {return parseInt(a, 10) + parseInt(b, 10)})
}
var myNumbers =[num1, num2, num3]
var findLargest = function(array){
var answer
var largest = 0
array.forEach(function(input){
// check if this is the largest sum
if (sum(input) == largest){
// check if there is already a running set of equal sums
if (typeof(answer) == Object) answer.push(input)
// create set of equal sums if not
else answer = [answer, input]
}
else if (sum(input) > largest) {
largest = sum(input)
answer = input
}
})
return answer
}
alert(findLargest(myNumbers))
https://jsfiddle.net/gmebk2Ly/7/
This also checks to see if there are multiple inputs that are equal
If you want to sort the list by the sums of the digits, you can do the following. The comparator function finds the sum of the digits in the members of the list, then compares them. If you just wanted to sum the digits in the string, you can just extract the code that does this from this solution too.
myNumbers.sort(function(a,b) {
var sumA = 0;
var sumB = 0;
a.split("").forEach(function(digit) {
sumA+=parseInt(digit);
});
b.split("").forEach(function(digit) {
sumB+=parseInt(digit);
});
return sumA-sumB;
});
Let's break this down into two sub-problems: first, finding the sum of digits; second, finding the maximum value of an array. For the second, we already have Math.max.
For the first, we'll break it down even further and first write a function just to get the digits:
function digits(x) { return String(x).match(/\d/g).map(Number); }
To sum up the digits, we just say
function sumDigits(x) { return sum(digits(x)); }
For sum, you can find many examples here on SO, but the simplest one is
function sum(array) { return array.reduce(add, 0); }
add is easy enough:
function add(a, b) { return a + b; }
Now, to get the maximum sum of digits from each element of an array:
function maxSumDigits(array) { return Math.max(...array.map(sumDigits)); }
The above uses ES6 spread operator. In ES5:
return Math.max.apply(0, array.map(sumDigits));
The advantage of writing your code this way is first, you end up with useful little utility routines that you can re-use; second, the code is easier to read and prove to yourself that it's right; and third, it's easier to deal with spec changes, such as wanting to find the minimum instead of the maximum, of the product of digits instead of the sum.
function digits(x) { return String(x).match(/\d/g) . map(Number); }
function sumDigits(x) { return sum(digits(x)); }
function sum(array) { return array . reduce(add, 0); }
function add(a, b) { return a + b; }
function maxSumDigits(array) { return Math.max(...array . map(sumDigits)); }
console.log(maxSumDigits([1234, 3456]));
This returns the largest sum. To find the element whose digits have the largest sum, the easiest way would be to remember the array of sums of digits, then look that up:
function maxSumDigits(array) {
var sums = array . map(sumDigits);
var max = Math.max(...sums);
return array[sums.indexOf(max)];
}
Related
I am interested in finding the credit card number whose digits sum to the largest number. If more than one has the same largest sum of digits, I want the last one in the list with that sum.
I am trying to write a single function that takes one argument. That argument will be an array of credit card numbers. Assume the array can have any number of credit card numbers and each one is a string of digits and dashes. The function should return the credit card number that has the largest sum of digits.
Here is what I have so far-
function getSum(stringLength) {
var stringLength = ['1476-0089-5132-7420', '2034-6002-3978-5567', '6647-1123-5895-0038'];
var i;
for (i = 0; i < stringLength; i++);
for (string = 0; string < [3]; stringLength++);
//stringLength + i =Sum ;
if (0 > 1, 2) {
return string(0);
} else if (1 > 0, 2) {
return string(1);
} else(2 > 1, 0) {
return string(2);
}
console.log('1476-0089-5132-7420', '2034-6002-3978-5567', '6647- 1123-5895-0038');
console.log('The Larget Sum is:' + true);
}
/*criteria for code: Contain all variables and code needed within a function.
Have that function take one argument which will be an array of credit card number strings.
Determine the sum of digits for each credit card number.
Determine which credit card number has the last largest sum of digits.
Use a return statement to return the required card number in its’ original form.*/
You can try this approach:
Note: ;is used to end a statement, so when you do for(...); loop ends there and it does not do anything.
var cardNos = ['1476-0089-5132-7420', '2034-6002-3978-5567', '6647-1123-5895-0038'];
var largestSum = cardNos.reduce(function(p,c){
return Math.max(p, getSumOfDigits(c))
}, 0);
function getSumOfDigits(str){
var s = str.replace(/[^0-9]/g, '').split("");
return s.reduce(function(p,c){ return +p + +c});
}
console.log(largestSum);
I am doing a challenge on Coderbyte and I would be grateful for any advice on my question:
The challenge given to me:
"Using the JavaScript language, have the function ArrayAdditionI(arr)
take the array of numbers stored in arr and return the string true if
any combination of numbers in the array can be added up to equal the
largest number in the array, otherwise return the string false.
For example: if arr contains [4, 6, 23, 10, 1, 3] the output should
return true because 4 + 6 + 10 + 3 = 23. The array will not be empty,
will not contain all the same elements, and may contain negative numbers. "
The way I attempted to solve it: http://jsfiddle.net/reLsg0fg/
function ArrayAdditionI(arr){
var newArr=arr.sort(); // sorted from smallest to largest.
var largestNum=newArr.slice(-1); // Gets the last number, which would be the largest.
var loopArr=arr.sort().pop(); // Takes out the largest number for adding later.
var result=0;
for(var i=0; i<loopArr.length; i++){ // loops through all numbers.
if(result/largestNum !== 1){ //when you divide a number by itself it will be 1.
result+=loopArr[i]; // keep adding each number until get largest number.
}else if(result === largestNum){
return true;
}
}
return false;
}
// TESTS
console.log("-----");
console.log(ArrayAdditionI([4,6,23,10,1,3]));
console.log(ArrayAdditionI([5,7,16,1,2]));
console.log(ArrayAdditionI([3,5,-1,8,12]));
I'm supposed to get true, false, true. But I get false, false, false as if something is wrong within my loop. JSFiddle: http://jsfiddle.net/reLsg0fg/
I would appreciate any suggestions. Thank you ^^
Sort Array using
arr.sort(function (a, b) { return a - b })
I have tried to solve this problem with a for loop but I missed the fact that the challenge
is not asking that all numbers need to add up to equal the largest num, but it is also possible to
add up to the largest num if we take some numbers out. Thus I decided to solve with recursion.
Tips:
* The Math.max.apply() method takes an array and returns the largest number. Note that it usually works on strings as Math.max().
* the sort() method can take a parameter to further expand it's purpose. Usually it only
sorts strings, but to sort numbers we include a function that finds which number is bigger.
* First get the largest number.
* Sort the array and remove the largest number to be used for recursion later.
* Create a recursion function that checks if the numbers add up to the largest number, and if not, check that if some numbers in array are subtracted from the largest num they are equal to the largest number.
function ArrayAdditionI(array){
var largestNum = Math.max.apply(0, array); // gets the largest number in array.
array.sort(function(a,b){ return a-b;}).pop(); // sorts array and removes last(largest) number.
function recursionCheck(arr, sum){
// the base case when array empty.
if(arr.length === 0){
return sum === 0;
}
var arrBeginNum=arr[0];
// for every recursion take away one number(the first one in this case).
arr = arr.slice(1);
// first check if numbers sum up to largest num if not, check if removing numbers adds up to largest num.
return recursionCheck(arr, sum) || recursionCheck(arr, sum - arrBeginNum);
}
// recursion needs to be called for it to start.
return recursionCheck(array, largestNum);
}
// TESTS
console.log("-----");
console.log(ArrayAdditionI([1,2,3,5,4])); ==> true
console.log(ArrayAdditionI([21,10,12,9,2])); ==> true
console.log(ArrayAdditionI([4,6,23,10,1,3])); ===> true
console.log(ArrayAdditionI([5,7,16,1,2])); ===> false
console.log(ArrayAdditionI([3,5,-1,8,12])); ===> true
This might not be the complete solution yet, but here are the JavaScript-Problems:
largestNum was an array in you algorithm
.sort() was not working
function ArrayAdditionI(arr){
var largestNum = Math.max.apply(0, arr); // Gets the last number, which would be the largest.
arr.sort(function(a, b){return a-b})
arr.pop(); // Takes out the largest number for adding later.
var result=0;
Also use if(result !== largestNum) {, Division is expensive and might have unexpected results with floating-point numbers.
Thats it for your JavaScript. But I am pretty sure the Algorithm is wrong - but I think this is up to you
Note that the example [4, 6, 23, 10, 1, 3] => 4 + 6 + 10 + 3 = 23 is not just adding up the lowest to the biggest value to try and match it.
A possible example of a solution for the problem.
How this works:
First sort all items descending
Shift the first element to largest
Call the recursive function y with the reduced array, the largest value and a variable which holds an empty array for the successfully added items.
The recursive function works basically in two parts
Test if the remaining sum is zero, if so the result is achieved and return true, which finished the function.
If not iterate through the array and
Make a copy from the array
Get the value from the position with splice
Test, if the value is smaller or equal the remaining sum and the result of the call of y with the shorted array, sum minus value and a new array with the used items and the acual item.
If true return true and finish the function.
If not finished before return false.
function x(array) {
function y(a, s, result) {
var aa, i, v;
if (s === 0) {
document.write('<pre>result: ' + JSON.stringify(result, 0, 4) + '</pre>');
return true;
}
for (i = 0; i < a.length; i++) {
aa = a.slice();
v = aa.splice(i, 1)[0];
if (v <= s && y(aa, s - v, result.concat(v))) {
return true;
}
}
return false;
}
var largest,
r = [];
array.sort(function (a, b) { return b - a; });
largest = array.shift();
document.write('largest value: ' + largest + '<br>');
return y(array, largest, r);
}
document.write(x([4, 6, 23, 10, 1, 3]) + '<hr>');
document.write(x([5, 7, 16, 1, 2]) + '<hr>');
document.write(x([3, 5, -1, 8, 12]));
Thanks #mar
Here is a version in Kotlin if someone needs
private fun returnResult(arr: Array<Int>): Boolean {
arr.sort()
val largestNumber = arr.last()
val arrWithoutLargest = arr.dropLast(1).toTypedArray()
return recursionCheck(arrWithoutLargest, largestNumber)
}
private fun recursionCheck(arr: Array<Int>, sum:Int): Boolean {
if (arr.isEmpty()) return sum == 0
val arrBeginNum = arr[0]
val arr2 = arr.drop(1).toTypedArray()
return recursionCheck(arr2, sum) || recursionCheck(arr2, sum - arrBeginNum)
}
Let's say I have a string of numbers separated by spaces and I want to return the highest and lowest number. How could that best be done in JS using a function? Example:
highestAndLowest("1 2 3 4 5"); // return "5 1"
I would like the both numbers to be returned in a string. The lowest number first followed by a space then the highest number.
Here is what I have so far:
function myFunction(str) {
var tst = str.split(" ");
return tst.max();
}
You can use Math.min and Math.max, and use them in an array to return the result, try:
function highestAndLowest(numbers){
numbers = numbers.split(" ");
return Math.max.apply(null, numbers) + " " + Math.min.apply(null, numbers)
}
document.write(highestAndLowest("1 2 3 4 5"))
Below is a code that improves the solution and facilitates global use:
/* Improve the prototype of Array. */
// Max function.
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
// Min function.
Array.prototype.min = function() {
return Math.min.apply(null, this);
};
var stringNumbers = "1 2 3 4 5";
// Convert to array with the numbers.
var arrayNumbers = stringNumbers.split(" ");
// Show the highest and lowest numbers.
alert("Highest number: " + arrayNumbers.max() + "\n Lowest number: " + arrayNumbers.min());
OK, let's see how we can make a short function using ES6...
You have this string-number:
const num = "1 2 3 4 5";
and you create a function like this in ES6:
const highestAndLowest = nums => {
nums = nums.split(" ");
return `${Math.max(...nums)} ${Math.min(...nums)}`;
}
and use it like this:
highestAndLowest("1 2 3 4 5"); //return "5 1"
function highAndLow(numbers){
var temp = numbers.split(' ');
temp.sort(function(a,b){return a-b; });
return temp[temp.length-1] + ' ' + temp[0];
}
did a little differently:
first split into an array, then sorted ... and returned the last (maximum) element with the first (minimum) element
function highAndLow(numbers){
numbers = numbers.split(' ');
return ${Math.max(...numbers)} ${Math.min(...numbers)};
}
I want to Split a number into its digit (for example 4563 to 4 , 5 , 6 , 3 ) then addiction this digits. (for example: 4+5+6+3=18)
I can write code for 3 digit or 2 digit and ... numbers seperately but I cant write a global code for each number.
so this is my code for 2 digit numbers:
var a = 23
var b = Math.floor(a/10); // 2
var c = a-b*10; // 3
var total = b+c; // 2+3
console.log(total); // 5
and this is my code for 3 digit numbers:
var a = 456
var b = Math.floor(a/100); // 4
var c = a-b*100; // 56
var d = Math.floor(c/10); // 5
var e = c-d*10; // 6
var total = b+d+e; // 4+5+6
console.log(total); // 15
but I cant write a code to work with each number.How can I write a global code for each number?
In modern browsers you can do an array operation like
var num = 4563;
var sum = ('' + num).split('').reduce(function (sum, val) {
return sum + +val
}, 0)
Demo: Fiddle
where you first create an array digits then use reduce to sum up the values in the array
var num = 4563;
var sum = 0;
while(num > 0) {
sum += num % 10;
num = Math.floor(num / 10);
}
console.log(sum);
Do number%10(modulus) and then number/10(divide) till the number is not 0
I hope the following example is useful to you:
var text="12345";
var total=0;
for (i=0;i<text.length;i++)
{
total+= parseInt(text[i]);
}
alert(total);
This solution converts the number to string, splits it into characters and process them in the callback function (prev is the result from the previous call, current is the current element):
var a = 456;
var sum = a.toString().split("").reduce(function(prev, current){
return parseInt(prev) + parseInt(current)
})
Here is how I would approach the problem. The trick I used was to split on the empty string to convert the string to an array and then use reduce on the array.
function digitSum(n) {
// changes the number to a string and splits it into an array
return n.toString().split('').reduce(function(result, b){
return result + parseInt(b);
}, 0);
}
As mentioned by several other posters (hat tip to my commenter), there are several other good answers to this question as well.
Here is my solution using ES6 arrow functions as call back.
- Convert the number into a string.
- Split the string into an array.
- Call the map method on that array.
- Callback function parse each digit to an array.
let number = 65535;
//USING MAP TO RETURN AN ARRAY TO DIGITS
let digits = number.toString()
.split("")
.map(num => parseInt(num));
//OUTPUT TO DOM
digits.forEach(
digit =>
document.querySelector("#out").innerHTML += digit + "<br>"
);
<p id="out"></p>
1) You can cast input number to string, using .toString() method and expand it into array with spread (...) operator
const splitNumber = n => [ ...n.toString() ]
2) Another short way - using recursion-based solution like:
const splitNumber = n => n ? [ ...splitNumber(n/10|0), n%10 ] : []
I am beginner to javascript and i am getting unexpected output
here is the code
<script type="text/javascript">
function add(a,b)
{
x = a+b;
return x;
}
var num1 = prompt("what is your no.");
var num2 = prompt("what is another no.")
alert(add(num1,num2));
</script>
it should give output as a sum of two number entered by us on prompting but it is simply concatenating the two number and popping the output
This is because the prompt function returns a String and not a Number. So what you're actually doing is to request 2 strings and then concatenate them. If you want to add the two numbers together you'll have to convert the strings to numbers:
var num1 = parseFloat(prompt("what is your no."));
var num2 = parseFloat(prompt("what is another no."));
or simpler:
var num1 = +prompt("what is your no.");
var num2 = +prompt("what is another no.");
prompt returns a string, not a number. + is used as both an addition and concatenation operator. Use parseInt to turn strings into numbers using a specified radix (number base), or parseFloat if they're meant to have a fractional part (parseFloat works only in decimal). E.g.:
var num1 = parseInt(prompt("what is your no."), 10);
// radix -----^
or
var num1 = parseFloat(prompt("what is your no."));
When you prompt the user, the return value is a string, normal text.
You should convert the strings in numbers:
alert(add(parseInt(num1), parseInt(num2));
The return value of prompt is a string. So your add function performs the + operator on 2 strings, thus concatenating them. Convert your inputs to int first to have the correct result.
function add(a,b)
{
x = parseInt( a ) + parseInt( b );
return x;
}
In addition to the already provided answers: If you're using parseInt() / parseFloat(), make sure to check if the input in fact was a valid integer or float:
function promptForFloat(caption) {
while (true) {
var f = parseFloat(prompt(caption));
if (isNaN(f)) {
alert('Please insert a valid number!');
} else {
return f;
}
}
}
var num1 = promptForFloat('what is your no.');
// ...