javascript getting user input to an array - javascript

hello im trying to get the minumum value of this array am i adding the user input to the array propperly.
var highestMark=0;
var gradeAwarded;
var StudentArr= [Student];
var markArr = [mark];
var Student = prompt("Enter Student Name: ", "Ross");
var mark = prompt("Enter Student Mark: ", 50);
var max;
function min (mark){
var min = Number.Max_Value;
for(var i = 0; i < mark.length; i++)
if(mark[i] < min)
min = mark[i];
}
return mark;
var smallest = min (mark);
document.write(smallest);

Ok, it's possible, but the prompt method return a string and you can lead with this string the way you want. For sample, if you user type some values separated by a specific char , (for sample) you could use the split method and get this array, for sample:
var values = prompt("Eter values: ", "");
var result = values.split(',');
but your code looks fine, just convert the mark[i] to number, to sample:
function min (mark){
var min = Number.Max_Value;
for(var i = 0; i < mark.length; i++)
if(number(mark[i]) < min)
min = number(mark[i]);
return mark;
}

Related

I have a string with counts and alphabets in ordered manner i have to print the alphabets according to their count

var input = `2
6
z2k1o2
6
m2v1p2`
var newInput = input.split("\n")
//console.log(newInput.length)
var input_arr = input.trim().split("\n")
var n = Number(input_arr[0])
//console.log(input_arr)
for (var i = 1; i < input_arr.length; i = i + 2) {
var length = Number(input_arr[i])
var string = input_arr[i + 1].trim()
}
//console.log(string)
var newstring = string
//console.log(newstring)
var alpha = []
var num = []
for (i = 1; i < string.length; i += 2) {
num.push(string[i])
}
var newnum = num.map(Number)
//console.log(newnum)
for (i = 0; i < string.length; i += 2) {
alpha.push(string[i])
}
var newalpha = (alpha)
//console.log(newalpha)
var answer = []
for (i = 0; i < newnum.length; i++) {
for (j = 0; j < newnum[i]; j++) {
answer.push(newalpha[i])
}
}
console.log(answer.join(""))
Here I'm getting only one output can you please explain why And do you like share any other approach for this problem.
This is the input z2k1o2 and the output should be zzkoo
The input will follow this patter of alphabets ans counts..
I'd do this with a regular expression that captures pairs of (character, number) and uses the function-replacement mode of .replace() to generate the replacement string.
> "a2b1c2".replace(/([a-z])([0-9]+)/ig, (_, a, b) => a.repeat(+b))
"aabcc"
>"pos2es2".replace(/([a-z])([0-9]+)/ig, (_, a, b) => a.repeat(+b))
"possess"
Here's where you're running into your error:
for (var i = 1; i < input_arr.length; i = i + 2) {
var length = Number(input_arr[i])
var string = input_arr[i + 1].trim()
}
You're going through the entire input array and saving each of the lengths and strings, but you're overwriting the length and the string each time you read it - only the last length and last string are saved, and so only the last length and last string are processed / printed.

Why aren't the bigInts adding?

I made a NodeJS program that takes pairs of integers (m, n) as input and prints the sum of their factorials (facm, factn) on the console. I used the BigInteger.js library so that I can calculate using big numbers.
But when I input 20 1, the program just outputs the value of 20! instead of 20! + 1!. It doesn't add. Why?
(For some reason, it works for when the two inputs are the same, for example, 20 20. It also works when the values are smaller.)
var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var lines = input.split('\n');
var bigInt = require("big-integer");
for (var i = 0; lines[i] != ""; i++) {
var strings = lines[i].split(" ");
var m = parseInt(strings[0]);
var n = parseInt(strings[1]);
var factm = bigInt(1);
var factn = bigInt(1);
for (var a = m; a != 0; a--) {
factm = factm.multiply(a);
}
for (var b = n; b != 0; b--) {
factn = factn.multiply(b);
}
var sum = factm.add(factn);
console.log(sum.toString());
}
Replacing var sum = factm.add(factn) with var sum = factm.add(factn.toString()) solves the problem.

Create number range from input field

I have input field for ZIP, when user fill out field I want create two variables with first ground value.
example:
User type: 01250,
I need two variables with values 01000 and 02000
var zip = $('.js-zip-input').val();
var inputZip = zip % 1000;
var zipMax = zip - inputZip + 1000;
var zipMin = zip - inputZip;
This working for values when first char isn't 0
It's 'not working' because these are numbers, and it doesn't make sense to have a number 01000. This is really just 1000. If you really need to have the zero, you will have to turn your values into strings and add 0 to the beginning of them.
Is this what you wanted?
var zip = 1250;
var range = 1000;
var zipMin = Math.floor(zip/range) * range;
var zipMax = zipMin + range;
The code above gets the floor value of the zip input.
You can set up the range value as the difference of both outputs: in your case 1000 to 2000 would have a range of 1000. Give it a try.
As gavin pointed out, you cant have a leading 0 before the output unless you convert them to string. In this case, you can check for the length of the output (as strings) and add leading zeroes.
var outputLength = 5;
var zipMinOutput = "0".repeat(outputLength - zipMin.toString().length) + zipMin;
var zipMaxOutput = "0".repeat(outputLength - zipMax.toString().length) + zipMax;
The above code adds trailing zeroes for every missing character in the string.
(function(){
var zip = '00000140050';
var zeros = leading_zero(zip.toString().split('').map(Number)); //Number of zeros can be appended to min max values
alert(zeros);
var inputZip = zip % 1000;
var zipMax = zip - inputZip + 1000;
var zipMin = zip - inputZip;
alert(zipMax + ', ' + zipMin);
function leading_zero(x)
{
var n = 0;
for (var i = 0; i < x.length; i ++) {
if (x[i] == 0) n++;
else
break;
}
return n;
}
}());

Javascript: reducing down to one number

So I need to take a date and convert it into one single number by adding up each digit, and when the sum exceeds 10, I need to add up the two digits. For the code below, I have 12/5/2000, which is 12+5+2000 = 2017. So 2+0+1+7 = 10 & 1+0 = 1. I get it down to one number and it works in Firebug (output of 1). However, it is not working in a coding test environment I am trying to use, so I suspect something is wrong. I know the code below is sloppy, so any ideas or help reformatting the code would be helpful! (Note: I am thinking it has to be a function embedded in a function, but haven't been able to get it to work yet.)
var array = [];
var total = 0;
function solution(date) {
var arrayDate = new Date(date);
var d = arrayDate.getDate();
var m = arrayDate.getMonth();
var y = arrayDate.getFullYear();
array.push(d,m+1,y);
for(var i = array.length - 1; i >= 0; i--) {
total += array[i];
};
if(total%9 == 0) {
return 9;
} else
return total%9;
};
solution("2000, December 5");
You can just use a recursive function call
function numReduce(numArr){
//Just outputting to div for demostration
document.getElementById("log").insertAdjacentHTML("beforeend","Reducing: "+numArr.join(","));
//Using the array's reduce method to add up each number
var total = numArr.reduce(function(a,b){return (+a)+(+b);});
//Just outputting to div for demostration
document.getElementById("log").insertAdjacentHTML("beforeend",": Total: "+total+"<br>");
if(total >= 10){
//Recursive call to numReduce if needed,
//convert the number to a string and then split so
//we will have an array of numbers
return numReduce((""+total).split(""));
}
return total;
}
function reduceDate(dateStr){
var arrayDate = new Date(dateStr);
var d = arrayDate.getDate();
var m = arrayDate.getMonth();
var y = arrayDate.getFullYear();
return numReduce([d,m+1,y]);
}
alert( reduceDate("2000, December 5") );
<div id="log"></div>
If this is your final code your function is not outputting anything. Try this:
var array = [];
var total = 0;
function solution(date) {
var arrayDate = new Date(date);
var d = arrayDate.getDate();
var m = arrayDate.getMonth();
var y = arrayDate.getFullYear();
array.push(d,m+1,y);
for(var i = array.length - 1; i >= 0; i--) {
total += array[i];
};
if(total%9 == 0) {
return 9;
} else
return total%9;
};
alert(solution("2000, December 5"));
It will alert the result in a dialog.

I want to add all the values in the field Sum to the field Total but it is not working

Here, sums[i].value is getting right values but when I want to keep a grand total of all Sum, it is failing.
function calc() {
var amounts = document.getElementsByName("Amount");
var prices = document.getElementsByName("Price");
var sums = document.getElementsByName('Sum');
var tax = document.getElementsByName('Tax');
var total = document.getElementsByName('Total');
for (var i = 0; i < amounts.length; i++) {
sums[i].value = amounts[i].value * prices[i].value;
total[0].value = total[0].value + sums[i].value;
// only this line is not working
}
}
Plain HTML is strings, all the way down, and var amounts = document.getElementsByName("Amount"); followed by amounts.value means you now have string values. Since + is also a string operator, JavaScript will happily turn "2"+"4" into "24", which looks like it did maths, but wrong, when in fact it didn't do math at all.
Convert all values that need to be numbers into numbers, first:
var amounts = document.getElementsByName("Amount");
....
var amount = parseFloat(amounts.value); // NOW it's a number
...
Replace your code with :
for (var i = 0; i < amounts.length; i++) {
sums[i].value = parseFloat(amounts[i].value) * parseFloat(prices[i].value);
total[0].value = parseFloat(total[0].value) + parseFloat(sums[i].value);
// only this line is not working
}
sums[i].value = parseFloat(amounts[i].value) * parseFloat(prices[i].value);
total[0].value = parseFloat(total[0].value) + parseFloat(sums[i].value);
This should help you.
Remove the .value while adding and multiplying
function test()
{
var amounts = new Array();
amounts[0] = "4";
amounts[1] = "6";
amounts[2] = "10";
var prices = new Array();
prices[0] = "4";
prices[1] = "6";
prices[2] = "10";
var sums = new Array();
var total = 0;
for (var i = 0; i < amounts.length; i++) {
sums[i] = parseInt(amounts[i]) * parseInt(prices[i]);
total= parseInt(total) + parseInt(sums[i]);
// only this line is not working
//alert(total); is 152
}
}

Categories

Resources