javascript user input highest of 20 numbers - javascript

for this program, i need the user to enter 20 numbers and for the highest to be displayed. i have done a similar one with 4, which i will display below, however there must be an easier way that going through it all? any advice would be great.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function maxNum(num1, num2, num3, num4){
var max = 0;
if((num1 >= num2) && (num1 >= num3)){
max = num1;
}
else if((num2 >= num1) && (num2 >= num3) && (num3 >= num4)){
max = num2;
}
else if((num3 >= num1) && (num3 >= num2) && (num3 >= num4)){
max = num3;
}
else{
max = num4;
}
return max;
}
var arr = [];
for(i=0;i<4;i++){
arr[i] = parseInt(prompt("Enter a number"));
}
document.write(maxNum.apply(this, arr));
</script>
</body>
</html>

function findMaxNum(arr) {
return Math.max.apply(null, arr);
}
var arr = [];
for (var i = 0; i < 4; i++) {
arr[i] = parseInt(prompt('Enter a number'), 10);
}
var maxNum = findMaxNum(arr);
Math.max usually works with a series of numbers: Math.max(1, 4, 10) // 10, but here we use apply on the function so that it accepts an array instead.
(Note, added the radix for parseInt)
DEMO

Assuming that all values passed into your function will be numbers you can use Math.max with the arguments special variable.
function getMax()
{
if (Object.prototype.toString.call(arguments[0]) === '[object Array]') {
return Math.max.apply(null, arguments[0]);
}
return Math.max.apply(null, arguments);
}
var myArr = [2,4,6,8,10,12,14,16,18,20];
getMax(1,2,4,5,6,7,8,10); // 10
getMax(myArr); // 20
The example above allows an array or a list of arguments to be passed through. This allows you to reuse where required.

Yes, with Math.max.apply. It takes an object (null) and an array with the values.
function getMax(array) {
var i,
max = +array[0]; // the first element with implicit casting to number
for (i = 1; i < array.length; i++) { // loop throu all elements
if (+array[i] > max) { // with cast to number
max = array[i];
}
}
return max;
}
var userInput = ['1', 'a', '4', '-', '1000', '20'].filter(Number);
document.write(userInput + '<br>');
document.write(Math.max.apply(null, userInput) + '<br>');
document.write(getMax(userInput) + '<br>');

Related

Check Digit Sum Javascript- recursion [duplicate]

This question already has answers here:
Adding digits from a number, using recursivity - javascript
(6 answers)
Closed 8 months ago.
Looking for Javascript solution in recursion to get the sum of all digits in number until single digit come as result
For example, for the number is "55555" the sum of all digits is 25. Because this is not a single-digit number, 2 and 5 would be added, and the result, 7.
I tried the below solution based on the algorithm.
function getSum(n) {
let sum = 0;
while(n > 0 || sum > 9)
{
if(n == 0)
{
n = sum;
sum = 0;
}
sum += n % 10;
n /= 10;
}
return sum;
}
console.log(getSum("55555"));
This would kind of work, but I'm almost sure there's a beautiful one-line solution which I just don't see yet.
function singleDigitSum(str) {
str = [...str].reduce((acc, c) => { return Number(c) + acc }, 0)
while (str.toString().length > 1) {
str = singleDigitSum(str.toString());
}
return str
}
console.log(singleDigitSum("55555"))
Explanation:
As a first step in your function you reassign to the parameter passed to the function the result of a reducer function which sums up all numbers in your String. To be able to use Array.prototype.reduce() function, I'm spreading your str into an array using [...str].
Then, for as often as that reducer returns a value with more than one digit, rinse and repeat. When the while loop exits, the result is single digit and can be returned.
function checSumOfDigit(num, sum = "0") {
if (num.length == 1 && sum.length !== 1) {
return checSumOfDigit(Number(sum) + Number(num) + "", "0");
} else if (num.length == 1) {
return Number(sum) + Number(num);
}
num = num.split("")
sum = Number(sum) + Number(num.pop());
return checSumOfDigit(num.join(""), sum + "")
}
console.log(checSumOfDigit("567"));
console.log(checSumOfDigit("123"));
console.log(checSumOfDigit("55555"));
this code might be help you
If you need a recursion try this one
function CheckDigitSum(number) {
let nums = number.split('');
if (nums.length > 1) {
let sum = 0;
for (let i = 0; i < nums.length; i++) {
sum += Number(nums[i]);
}
return CheckDigitSum(sum.toString());
} else {
return parseInt(nums[0], 10);
}
}
Here you go:
function createCheckDigit(num) {
var output = Array.from(num.toString());
var sum = 0;
if (Array.isArray(output) && output.length) {
for ( i=0; i < output.length; i++){
sum = sum + parseInt(output[i]);
}
if ((sum/10) >= 1){
sum = createCheckDigit(sum);
}
}
return sum;
}
This can be calculated by recursive function.
function createCheckDigit(membershipId) {
// Write the code that goes here.
if(membershipId.length > 1){
var dgts = membershipId.split('');
var sum = 0;
dgts.forEach((dgt)=>{
sum += Number(dgt);
});
//console.log('Loop 1');
return createCheckDigit(sum + '');
}
else{
//console.log('Out of Loop 1');
return Number(membershipId);
}
}
console.log(createCheckDigit("5555555555"));
function checkid(num) {
let sum = 0;
let s = String(num);
for (i = 0; i < s.length; i++) {
sum = sum + Number(s[i]);
}
if(String(sum).length >= 2) return checkid(sum)
else return sum;
}
console.log(checkid(55555);

Sort three numbers in array from least to greatest

I have to create a function that takes 3 numbers. The function should return an array containing the numbers from least to greatest. So far I have this.I know it isn't correct but it's a start.I'm not using native functions as well. Can anyone give me some tips? Appreciate any help.
function leastToGreatest (num) {
var array = [];
var num1 = 0;
var num2 = 0;
var num3 = 0;
for (var i = 0; i < num.length; i++) {
if(num[i] < num[i] && num[i] < num[i]) {
num[i] = num1;
array.push(num1);
}
else if(num[i] > num[i] && num[i] < num[i]) {
num[i] = num2;
array.push(num2);
}
else if(num[i] > num[i] && num[i] > num[i])
num[i] = num3;
array.push(num3);
}
return array;
}
leastToGreatest(2,1,3);
I would suggest using two for loops to solve this problem. For example,
function sortArray(array) {
var temp = 0;
for (var i = 0; i < array.length; i++) {
for (var j = i; j < array.length; j++) {
if (array[j] < array[i]) {
temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
}
return array;
}
console.log(sortArray([3,1,2]));
With this function, no matter what size the array is it will always sort it.
The reason your function is not working (as is stated by #WashingtonGuedes) is that you are comparing the same value each time. As they said, you will reach the last statement and receive two false's, which causes you to test false for all three if statements. Your returned array, then, will be empty.
One suggestion is to not hard-code for three values, as you have done, but instead assume nothing and let the program do the hard work. As put in my code snippet, you can enter an array of any length and it will be sorted, not just where length is 3.
Your code as it is now currently does not work because you are comparing a number with itself, so it will always be equal (causing your sorting to do nothing). To get a working sort you could fix this or use array.prototype.sort.
Here is a fun little variation on this:
var sortingFunction = function(){
console.log([].slice.apply(arguments).sort(function(a, b) { return a - b; }));
}
sortingFunction(3,2,5,1);
You can pass in as many numbers as you want, not just three. If you want to limit it to three you can test it in the function:
var sortingFunction = function(){
var values = [].slice.apply(arguments);
if(values.length === 3) {
console.log(values.sort(function(a, b) { return a - b; }));
}
else
{
console.log('you didn\'t pass in three values');
}
}
sortingFunction(3,2,5,1);
sortingFunction(3,31,1);
If you just want an array with numbers arranged from least to greatest, you can use the sort() method with the following parameter:
array.sort(function(a,b){return(a-b)});
var array = [12,7,18,1];
array.sort(function(a,b){return (a-b)});
console.log(array); //Array should be arranged from least to greatest
If it's just three items you want to sort, you can do it quite easily with three comparisons and swaps:
if (num[0] > num[1])
{
// swap num[0] and num[1]
temp = num[0]; num[0] = num[1]; num[1] = temp;
}
if (num[0] > num[2])
{
// swap num[0] and num[2]
temp = num[0]; num[0] = num[2]; num[2] = temp;
}
// at this point, num[0] contains the smallest of the three numbers
if (num[1] > num[2])
{
// swap num[1] and num[2]
temp = num[1]; num[1] = num[2]; num[1] = temp;
}
// your three items are sorted
This is easy to prove correct by hand. Write the numbers 1, 2, and 3 on small pieces of paper, lay them out in random order, and then perform those steps above. No matter what order you start with, this will sort those three items.
Understand, the above only works for three items. If you want a way to sort any number of items, then you'll want to use the built-in sorting method.
var sort = function ([x, y, z]) {
var k = [x, y, z];
k[0] = Math.min(x, y, z);
if ((x < y && x > z) || (x < z && x > y)) {
k[1] = x;
}
else if ((y < x && y > z) || (y < z && y > x)) {
k[1] = y;
}
else {
k[1] = z;
}
k[2] = Math.max(x, y, z);
return k;
};

Javascript find max number from 3 inputs

I've just began Javascript in college. One task is to define and call a function to find the maximum number from 3 numbers entered by the user. I know there is a max() function but we were told to do it manually using if and else if.
I'm going wrong somewhere as you can see. It's just telling me the max is 0 everytime.
function maxNum(num1, num2, num3){
var max = 0;
if(num1 > num2){
if(num1 > num3){
num1 = max;
}
else{
num3 = max;
}
}
else{
if(num2 > num3){
num2 = max;
}
}
return max;
}
for(i=0;i<3;i++){
parseInt(prompt("Enter a number"));
}
document.write(maxNum());
Or you can use ES6 syntax, to compute largest of three numbers in easier way,
const largest = a => F = b => G = c => ((a > b && a > c) ? a : (b > a && b > c) ? b : c)
console.time()
console.log(largest(53)(30907)(23333))
console.timeEnd()
One problem you have is that you do not save the number the user inputs. You prompt them, parse it as an int and then nothing. You have to pass the 3 numbers into maxNum()
Here is a working example that uses proper left hand assignment and saves the number. Also it is a good idea to use >= instead of > because the user can enter 2 of the same number
function maxNum(num1, num2, num3){
var max = 0;
if((num1 >= num2) && (num1 >= num3)){
max = num1;
}
else if((num2 >= num1) && (num2 >= num3)){
max = num2;
}
else{
max = num3;
}
return max;
}
var arr = [];
for(i=0;i<3;i++){
arr[i] = parseInt(prompt("Enter a number"));
}
document.write(maxNum.apply(this, arr));
easiest way:
function maxNum(num1, num2, num3){
var tmp = 0;
if(num1 < num2 && num3 < num2) {
tmp = num2;
} else if(num3 < num1){
tmp = num1;
} else {
tmp = num3;
}
return tmp;
}
var arr = [];
for(var i = 0; i < 3; i++) {
arr[i] = prompt("Enter a number");
}
console.log(maxNum.apply(this, arr));
First in javascript and most modern programming language assignment like a = b copies the value of b into the variable a. It is not equivalent to b = a (which copies the value of a into the variable b). It's common to write a = 1, but a syntax error in most languages to write 1 = a. Thus, you don't want to write num1 = max, but instead write max = num1.
Second, your logic is incorrect as it won't treat the case maxNum(1,2,3) correctly. (Work through the logic when num1 < num2 and num2 < num3. The following code would work:
function maxNum(num1, num2, num3){
var max = 0;
if(num1 > num2){
if(num1 > num3){
max = num1;
}
else{
max = num3;
}
}
else{
if(num2 > num3){
max = num2;
} else {
max = num3;
}
}
return max;
}
Granted, I would probably write something like
function max3num(num1, num2, num3) {
var max_so_far = num1;
if (num2 > max_so_far) {
max_so_far = num2;
}
if (num3 > max_so_far) {
max_so_far = num3;
}
return max_so_far;
}
as the logic is very clear and it will be easy to extend to a max function with a larger number of elements to compare if necessary. (Adding in a for loop could make it variadic fairly easily). It is straightforward to see the logic works, because we start with the first element being the maximum so far (max_so_far), then consider if the second element is larger -- if so we assign that as max_so_far, and keep continuing until we have compared all the elements to the max_so_far. After we have considered each element once, we then return the max_so_far which will now be the maximum of all of them.
No real need for a function here, just compare them as the come in!
var max = 0;
for(var i=0;i<3;i++){
var val = parseInt(prompt("Enter a number"));
max = max > val ? max : val;
}
alert(max);
The updated direct answer is this :
function maxNum(num1, num2, num3){
return [num1, num2, num3].sort(function (a, b) { return b - a })[0];
}
If written like this, it can easily be modified to take any amount of numbers by passing it an array of said numbers.
var numArray = [num1, num2, num3, num4, ...];
function maxNum(numArray){
return numArray.sort(function (a, b) { return b - a })[0];
}
The details :
Take an array :
[5,42,16]
Now sort it.
[5,42,16].sort()
But this wont work because javascript .sort requires a function to be passed in. This function tells it how to sort the array.
This will sort it highest to lowest, e.g. a is less then b.
function (a, b) { return b - a }
This will sort it lowest to highest, e.g. b is less then a.
function (a, b) { return a - b }
So we add it in :
[5,42,16].sort(function (a, b) { return b - a })
But this returns the sorted array, not the maximum number.
So we pick the first element in the array :
[5,42,16].sort(function (a, b) { return b - a })[0]
Lastly, you can pull out the sort function. This is mostly for demo purposes though.
var maxSorter = function (a, b) { return b - a };
function maxNum(numArray){
return numArray.sort(maxSorter)[0];
}
//Raihan
// program to find the largest among three numbers
// take input from the user using Prompt
let num1 = parseFloat(prompt("Enter first number: "));
let num2 = parseFloat(prompt("Enter second number: "));
let num3 = parseFloat(prompt("Enter third number: "));
let largest = Math.max(num1, num2, num3);
// display the result
document.write("The largest number is " + largest);
**//another way**
const num1 = parseFloat(prompt("Enter first number: "));
const num2 = parseFloat(prompt("Enter second number: "));
const num3 = parseFloat(prompt("Enter third number: "));
// check the condition
if(num1 >= num2 && num1 >= num3) {
document.write("Largest Number : " + num1)
}
else if (num2 >= num1 && num2 >= num3) {
document.write("Largest Number : " + num2)
}
else {
document.write("Largest Number : " + num3)
}

Javascript Happy Numbers not working

Here I have a function that should take a number n into the disHappy(n) to check if all
n in [n-0) are happy.
Happy Numbers wikipedia
If I only run happyChecker(n), I can tell that 7 is happy, but disHappy(n) doesn't show it. It is as if it doesn't receive the true. I have used console.log()'s all over the place and happyChecker(n) shows a number that SHOULD return true. When I placed a console.log() above the return true; for if(newNum===1), it showed that it branched into that branch but it just didn't seem to return the true.
function happyChecker(n) {
var arr = [];
var newNum = 0;
//here I split a number into a string then into an array of strings//
num = n.toString().split("");
for (var i = 0; i < num.length; i++) {
arr[i] = parseInt(num[i], 10);
}
//here I square each number then add it to newNum//
for (var i = 0; i < arr.length; i++) {
newNum += Math.pow(arr[i], 2);
}
//here I noticed that all unhappy numbers eventually came into one of these three//
//( and more) numbers, so I chose them to shorten the checking. A temporary solution for sure//
if (newNum === 58 || newNum === 4 || newNum == 37) {
return false;
}
if (newNum === 1) {
return true;
} else {
happyChecker(newNum);
}
}
function disHappy(num) {
for (j = num; j > 0; j--) {
if (happyChecker(j)) {
console.log(j + " is a Happy Number. It's so happy!!!.");
}
}
}
When you recurse, you need to return the value returned:
if (newNum === 1) {
return true;
} else {
return happyChecker(newNum);
}
You also should declare "num" with var.
I'm ordinarily not a "code golfer", but this is a good example of how the (new-ish) iterator utility methods on the Array prototype can clean up code. You can use the .reduce() function to traverse the array of digit characters and do the work of squaring and summing all at once:
var newNum = n.toString()
.split('')
.reduce(function(sum, digit) {
return sum + (+digit * +digit);
}, 0);
The call to .toString() returns a string, then .split('') gives you an array. Then .reduce() starts with an initial sum of 0 and for each element of the array (each digit), it adds to it the square of that digit. (Instead of parseInt() I just used the + unary operator; we know for sure that each string will be a valid number and an integer.)
You need to add return to the happyChecker call.
return happyChecker(newNum);
see:
http://jsfiddle.net/YjgL8/2/
here is my implementation
var getSum = function (n) {
if (!n >= 0) return -1;
var digits = n.toString().split("");
var sum = 0;
for (var i = 0; i < digits.length; i++) {
var digit = parseInt(digits[i], 10);
sum += digit * digit;
}
return sum;
}
/**
* #param {number} n
* #return {boolean}
*/
var isHappy = function(n, visited) {
if (n < 0) return false;
if (n === 1) return true;
if (typeof visited === 'undefined') visited = {};
sum = getSum(n);
if (visited[sum]) return false; // cycle
visited[sum] = true;
return isHappy(sum, visited);
};
Complete Example of finding happy numbers in range of custom number.
function happyNumbers() {
var result = document.getElementById("happy-result")
var inputy = parseInt(document.getElementById("happyValue").value)
result.innerHTML=""
for (i = 1; i < inputy; i++) {
(happy(i, i))
}
}
function happy(value,value2) {
var result = document.getElementById("happy-result")
var lengthNum = value.toString().length;
var resultNumbers = 0
for (var b = 0 ; b < lengthNum; b++) {
resultNumbers = resultNumbers + parseInt(value.toString().charAt(b)) * parseInt(value.toString().charAt(b))
}
if (resultNumbers == 4) {
return false
} else if (resultNumbers == 1) {
result.innerHTML += "<br> happy number " + i
return true
}else{
happy(resultNumbers, value2);
}
}
window.onload=happyNumbers()
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="panel panel-default">
<div class="panel-heading">happy numbers</div>
<div class="panel-body">
<label>Enter the number that you want ot have see happy numbers uo to it</label>
<input id="happyValue" oninput="happyNumbers()" value="100" class="form-control" />
<div id="happy-result"></div>
</div>
</div>

Division in javascript

function subtraction(num1, num2){
var num3;
num3 = num1 - num2;
document.writeln("Difference "+ num3);
return (num3);
}
function division(num1, num2){
difference = parseFloat(subtraction());
var x;
while(difference > 0){
difference = num1-num2;
x = x + 1;
}
document.writeln("Quotient" + x);
}
Hi! I wanted to do a division function but the catch is I will not use "/". This is what I got and so far this prints out "undefined" and if I stated x = 0 it will print out "0".
I fixed some problems with your code:
function division(num1, num2){
var difference = num1-num2; // difference is now a local variable
var x = 0; // x should be initialized
while(difference > 0){
difference = difference-num2; // difference should change, not always be num1-num2
x = x + 1;
}
console.log("Quotient" + x);
console.log("Remainder" + (difference+num2));
}
http://jsbin.com/UQIqejo/1/edit
You still have some problems with the algorithm itself, as num2 being less than or equal to 0 will result in an infinite loop, but i expect finding those problems is part of the fun.
EDIT: Smaller version of the same code:
function divisionSmall(a,b) {
var x = 0;
while ((a-=b) > 0) x++;
console.log('Quotient', x);
console.log('Remainder', a+b);
}
EDIT2: Correct division:
function divisionSmall(a,b) {
var x = 0;
while ((a-=b) > 0) x++;
return [x, a+b];
}
function divisionCorrect(a,b) {
var ans;
if (b === 0) return ['INF', 0];
if ((a > 0) && (b > 0)) {
return divisionSmall(a,b);
}
if ((a > 0) && (b < 0)) {
ans = divisionSmall(a,-b);
return [-ans[0], ans[1]];
}
if ((a < 0) && (b > 0)) {
ans = divisionSmall(-a,b);
return [-ans[0] - 1, b-ans[1]];
}
if ((a < 0) && (b < 0)) {
ans = divisionSmall(-a,-b);
return [ans[0] + 1, -b-ans[1]];
}
}
console.log(divisionCorrect(11,3)); // 3, 2
console.log(divisionCorrect(11,-3)); // -3, 2
console.log(divisionCorrect(-11,3)); // -4, 1
console.log(divisionCorrect(-11,-3)); // 4, 1
There is still the challenge of doing the logic without ifs :). Good luck.
If your doing numbers their is a simpler way to do this using recursion:
function divide(num,denom) {
if (num < denom) return 0;
return (1 + divide(num - denom, denom));
}
For negative numbers you would have to extend this to track if numbers were less than 0. Also, while concise and neat, this breaks down for large numerators and small denominators as the max call stack size will be exceeded.
I believe your issue is with your while loop. If the subtraction method returns a negative number it will not compute.
User Math.abs to get absolute value.
<script>
function division(num1, num2){
var difference = Math.abs(parseFloat(subtraction(num1, num2)));
var x = 0;
while(difference > 0){
difference = difference-num2;
x = x + 1;
}
document.writeln("Quotient" + x);
}
function subtraction(num1, num2){
var num3;
num3 = num1 - num2;
document.writeln("Difference "+ num3); return (num3);
}
</script>

Categories

Resources