How to sum up distinct value using javascript - javascript

I want to try and sum up distinct value from a list.. currently i am able to do so if theres only 2 similar record. If theres more than 2 i am not able to do the checking. Following is the javascript code:
function validateData(){
var total = document.frm.size.value;
var msg="";
var tbxA;
var tbxB;
var tbxA2;
var tbxB2;
var tbxC;
var totalValue =0;
var repeatedValue= 0;
var row = 0;
var row2 = 0;
for(var i=0; i<parseInt(total); i++){
tbxA = document.getElementById('tbx_A'+i).value;
tbxB = document.getElementById('tbx_B'+i).value-0;
tbxC = document.getElementById('tbx_C'+i).value;
for(var j=i+1; j<parseInt(total); j++){
tbxA2 = document.getElementById('tbx_A'+j).value;
tbxB2 = document.getElementById('tbx_B'+j).value-0;
if (tbxA==tbxA2) {
totalValue = tbxB + tbxB2;
}
if (totalValue != tbxC) {
repeatedValue= 1;
row = i;
row2 = j;
msg+="*total value does not add up at row " +(row2+1);
break;
}
}
if(repeatedValue== 1){
break;
}
}
return msg;
}
For example A:type of fruit, B: total of each fruit, C: how many bought at a time
total of C should be equal to B. i.e Apple: 3+3+4 = 10. So if the total is not equals to 10 it should prompt me an error.
A B C
Apple 10 3
Orange 10 10
Apple - 3
Apple - 4
My code above will prompt error bt it doesnt go beyond 2nd occurence of Apple.
So yes, how should i go about to ensure it loop through the whole list to sum up all similar values?
Thanks in advance for any possible help!

Try this:
var total = +document.frm.size.value,
data = {};
for(var i=0; i<total; ++i) {
var key = document.getElementById('tbx_A'+i).value;
data[key] = data[key] || {B:0, C:0};
data[key].B += +document.getElementById('tbx_B'+i).value || 0;
data[key].C += +document.getElementById('tbx_C'+i).value || 0;
}
for(var i in data) {
if(data.hasOwnProperty(i) && data[i].B != data[i].C) {
return "total value does not add up";
}
}
return "";
Some comments:
parseInt (and parseFloat) is very slow. + operator before string converts it to a number much faster. But if you really want to make sure the numbers are integers, use Math.floor(), Math.round(), Math.ceil() or the faster but illegible |0.
In case you really want parseInt (e.g. you want to convert '123foobar' into 123), always use a radix. For example: parseInt('123', 10)
Avoid doing calculations at the condition of a loop, because they run at each iteration. Just do the calculation once before the loop and save the result in a variable.

Related

free shipping ... if shopping chart total is greater than $35 ... user input unless total is more $35 in JavaScript

I m not sure what i m doing wrong. Thanks in advance for helping me in this matter.
var sum = 0;
var pricecheck = 35;
while (sum < pricecheck) {
var userinput = prompt("Please enter the cost of the item...");
var num1 = parseInt(userinput);
submitprice.push(num1);
for (i = 0; i < submitprice.length; i++) {
sum += submitprice[i];
}
}
alert("free shipping.");
Declare sum to zero each time you are executing the sum of items. Or else it will keep on adding to the sum that was calculated in previous iteration.
Also your submitprice seems to be undefined. I have initilaized it as an empty array.
Working Fiddle
var sum = 0;
var pricecheck = 35;
const submitprice = [];
while (sum < pricecheck) {
var userinput = prompt("Please enter the cost of the item...");
var num1 = parseInt(userinput);
submitprice.push(num1);
sum = 0;
for (i = 0; i < submitprice.length; i++) {
sum += submitprice[i];
}
}
alert("free shipping.");
To start, you need to create an empty array to store the totals in. For this, I will call it "cart":
var cart = [];
Next, I would suggest creating an if statement to check if the input is a number:
var num1 = parseInt(userinput);
if(isNaN(userinput){
alert("Please enter a number");
continue;
}
You don't need the for loop to add the input to the sum, just remove the loop:
sum += userinput
After the loop, you would push to the cart:
cart.push(num1)
Finally, you need to check if the sum is more than free shipping
if(sum >= pricecheck) {
alert("You qualify for free shipping!")'
}
Then just output the result to the console with a pipe (|) concatenated between the numbers.
console.log(cart.join(" | ")
var sum = 0;
var cart = [];
var pricecheck = 35;
while (sum < pricecheck) {
var userinput = prompt("Please enter the cost of the item...");
if (userinput === null) {
break;
}
var num1 = parseInt(userinput);
if (isNaN(userinput)) {
alert("Please enter a number");
continue;
}
cart.push(num1);
sum += num1;
}
if (sum >= pricecheck) {
alert("free shipping.");
}
I took a look at this assignment again to refresh on what was asked for this question. You do not need to have that for loop at all within the while loop. Within each iteration of the while loop, you are asking the user for the price of their next item, adding it to the shopping cart, and also adding it to a running total (this total being your "sum"). This running total does not need to be re-calculated each time inside of the while loop because you would have done that in a single line. You are trying to calculate the price, starting at 0, each time you loop through the while loop (using your for loop). But this is not needed as you already have a running total that can be added to each time the user enters a value.
"Austin Caron" explained it well but for this assignment we do not need to do user authentication.
P.S. Try your best to avoid asking questions directly about an assignment and ask more general questions about a concept or idea you are struggling with.

project euler #1 , hacker rank

i am trying to do project euler # 1 with Javascript in HackerRank. Can someone give me a hints in what's wrong with my code. the result is always zero.
I run my function in my google chrome console, then i input processData(10), it gives me 23. I input processData(100), it gives me 2318.
When i try to use my code in the console from Hacker rank, it output the result as zero, like it didn't pass the first test which is 0.
Did anyone tried to solve some problem in hackerrank in javascript?
function processData(input) {
var result = []
var total=0
function findMultipleThreeAndFive(n){
var i = 0;
for(i ; i < n ;i++){
if(i%3 == 0 || i%5 == 0){
result.push(i);
}
}
}
findMultipleThreeAndFive(input)
function sum(){
for(var j = 0; j< result.length ;j++){
total += result[j]
}
return total;
}
sum()
console.log(total)
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
First off all, your code works: http://jsfiddle.net/azggks5a/ , but I thought I would show you how I would solve it:
I suggest you use ES6 sets, because they handle the uniqueness of your values.
I began by iterating through the multiples I wanted. I then multiplied the iterated multiple by every number upto belowThis. If the result was lower than belowThis I added the result to the set, otherwise I didn't.
Here's the code:
var multiplesOf = [3,5];
var belowThis = 10;
var multiples = new Set();
var totalOfMultiples = 0;
multiplesOf.forEach(function(element, index){
for(var i=0;i<belowThis;i++) {
if(multiplesOf[index]*i<belowThis) {
multiples.add(multiplesOf[index]*i);
}
}
});
multiples.forEach(function(element, index){
totalOfMultiples+=element;
});
console.log(totalOfMultiples);
You can change the multiples you wish to check, and to solve the question you would increase belowThis to 1000, and get a result of 233168.

Efficiently find every combination of assigning smaller bins to larger bins

Let's say I have 7 small bins, each bin has the following number of marbles in it:
var smallBins = [1, 5, 10, 20, 30, 4, 10];
I assign these small bins to 2 large bins, each with the following maximum capacity:
var largeBins = [40, 50];
I want to find EVERY combination of how the small bins can be distributed across the big bins without exceeding capacity (eg put small bins #4,#5 in large bin #2, the rest in #1).
Constraints:
Each small bin must be assigned to a large bin.
A large bin can be left empty
This problem is easy to solve in O(n^m) O(2^n) time (see below): just try every combination and if capacity is not exceeded, save the solution. I'd like something faster, that can handle a variable number of bins. What obscure graph theory algorithm can I use to reduce the search space?
//Brute force
var smallBins = [1, 5, 10, 20, 30, 4, 10];
var largeBins = [40, 50];
function getLegitCombos(smallBins, largeBins) {
var legitCombos = [];
var assignmentArr = new Uint32Array(smallBins.length);
var i = smallBins.length-1;
while (true) {
var isValid = validate(assignmentArr, smallBins, largeBins);
if (isValid) legitCombos.push(new Uint32Array(assignmentArr));
var allDone = increment(assignmentArr, largeBins.length,i);
if (allDone === true) break;
}
return legitCombos;
}
function increment(assignmentArr, max, i) {
while (i >= 0) {
if (++assignmentArr[i] >= max) {
assignmentArr[i] = 0;
i--;
} else {
return i;
}
}
return true;
}
function validate(assignmentArr, smallBins, largeBins) {
var totals = new Uint32Array(largeBins.length);
for (var i = 0; i < smallBins.length; i++) {
var assignedBin = assignmentArr[i];
totals[assignedBin] += smallBins[i];
if (totals[assignedBin] > largeBins[assignedBin]) {
return false;
}
}
return true;
}
getLegitCombos(smallBins, largeBins);
Here's my cumbersome recursive attempt to avoid duplicates and exit early from too large sums. The function assumes duplicate elements as well as bin sizes are presented grouped and counted in the input. Rather than place each element in each bin, each element is placed in only one of duplicate bins; and each element with duplicates is partitioned distinctly.
For example, in my results, the combination, [[[1,10,20]],[[4,5,10,30]]] appears once; while in the SAS example in Leo's answer, twice: once as IN[1]={1,3,4} IN[2]={2,5,6,7} and again as IN[1]={1,4,7} IN[2]={2,3,5,6}.
Can't vouch for efficiency or smooth-running, however, as it is hardly tested. Perhaps stacking the calls rather than recursing could weigh lighter on the browser.
JavaScript code:
function f (as,bs){
// i is the current element index, c its count;
// l is the lower-bound index of partitioned element
function _f(i,c,l,sums,res){
for (var j=l; j<sums.length; j++){
// find next available duplicate bin to place the element in
var k=0;
while (sums[j][k] + as[i][0] > bs[j][0]){
k++;
}
// a place for the element was found
if (sums[j][k] !== undefined){
var temp = JSON.stringify(sums),
_sums = JSON.parse(temp);
_sums[j][k] += as[i][0];
temp = JSON.stringify(res);
var _res = JSON.parse(temp);
_res[j][k].push(as[i][0]);
// all elements were placed
if (i == as.length - 1 && c == 1){
result.push(_res);
return;
// duplicate elements were partitioned, continue to next element
} else if (c == 1){
_f(i + 1,as[i + 1][1],0,_sums,_res);
// otherwise, continue partitioning the same element with duplicates
} else {
_f(i,c - 1,j,_sums,_res);
}
}
}
}
// initiate variables for the recursion
var sums = [],
res = []
result = [];
for (var i=0; i<bs.length; i++){
sums[i] = [];
res[i] = [];
for (var j=0; j<bs[i][1]; j++){
sums[i][j] = 0;
res[i][j] = [];
}
}
_f(0,as[0][1],0,sums,res);
return result;
}
Output:
console.log(JSON.stringify(f([[1,1],[4,1],[5,1],[10,2],[20,1],[30,1]], [[40,1],[50,1]])));
/*
[[[[1,4,5,10,10]],[[20,30]]],[[[1,4,5,10,20]],[[10,30]]],[[[1,4,5,20]],[[10,10,30]]]
,[[[1,4,5,30]],[[10,10,20]]],[[[1,4,10,20]],[[5,10,30]]],[[[1,4,30]],[[5,10,10,20]]]
,[[[1,5,10,20]],[[4,10,30]]],[[[1,5,30]],[[4,10,10,20]]],[[[1,10,20]],[[4,5,10,30]]]
,[[[1,30]],[[4,5,10,10,20]]],[[[4,5,10,20]],[[1,10,30]]],[[[4,5,30]],[[1,10,10,20]]]
,[[[4,10,20]],[[1,5,10,30]]],[[[4,30]],[[1,5,10,10,20]]],[[[5,10,20]],[[1,4,10,30]]]
,[[[5,30]],[[1,4,10,10,20]]],[[[10,10,20]],[[1,4,5,30]]],[[[10,20]],[[1,4,5,10,30]]]
,[[[10,30]],[[1,4,5,10,20]]],[[[30]],[[1,4,5,10,10,20]]]]
*/
console.log(JSON.stringify(f([[1,1],[4,1],[5,1],[10,2],[20,1],[30,1]], [[20,2],[50,1]])));
/*
[[[[1,4,5,10],[10]],[[20,30]]],[[[1,4,5,10],[20]],[[10,30]]],[[[1,4,5],[20]],[[10,10,30]]]
,[[[1,4,10],[20]],[[5,10,30]]],[[[1,5,10],[20]],[[4,10,30]]],[[[1,10],[20]],[[4,5,10,30]]]
,[[[4,5,10],[20]],[[1,10,30]]],[[[4,10],[20]],[[1,5,10,30]]],[[[5,10],[20]],[[1,4,10,30]]]
,[[[10,10],[20]],[[1,4,5,30]]],[[[10],[20]],[[1,4,5,10,30]]]]
*/
Here's a second, simpler version that only attempts to terminate the thread when an element cannot be placed:
function f (as,bs){
var stack = [],
sums = [],
res = []
result = [];
for (var i=0; i<bs.length; i++){
res[i] = [];
sums[i] = 0;
}
stack.push([0,sums,res]);
while (stack[0] !== undefined){
var params = stack.pop(),
i = params[0],
sums = params[1],
res = params[2];
for (var j=0; j<sums.length; j++){
if (sums[j] + as[i] <= bs[j]){
var _sums = sums.slice();
_sums[j] += as[i];
var temp = JSON.stringify(res);
var _res = JSON.parse(temp);
_res[j].push(i);
if (i == as.length - 1){
result.push(_res);
} else {
stack.push([i + 1,_sums,_res]);
}
}
}
}
return result;
}
Output:
var r = f([1,5,10,20,30,4,10,3,4,5,1,1,2],[40,50,30]);
console.log(r.length)
console.log(JSON.stringify(f([1,4,5,10,10,20,30], [40,50])));
162137
[[[30],[1,4,5,10,10,20]],[[10,30],[1,4,5,10,20]],[[10,20],[1,4,5,10,30]]
,[[10,30],[1,4,5,10,20]],[[10,20],[1,4,5,10,30]],[[10,10,20],[1,4,5,30]]
,[[5,30],[1,4,10,10,20]],[[5,10,20],[1,4,10,30]],[[5,10,20],[1,4,10,30]]
,[[4,30],[1,5,10,10,20]],[[4,10,20],[1,5,10,30]],[[4,10,20],[1,5,10,30]]
,[[4,5,30],[1,10,10,20]],[[4,5,10,20],[1,10,30]],[[4,5,10,20],[1,10,30]]
,[[1,30],[4,5,10,10,20]],[[1,10,20],[4,5,10,30]],[[1,10,20],[4,5,10,30]]
,[[1,5,30],[4,10,10,20]],[[1,5,10,20],[4,10,30]],[[1,5,10,20],[4,10,30]]
,[[1,4,30],[5,10,10,20]],[[1,4,10,20],[5,10,30]],[[1,4,10,20],[5,10,30]]
,[[1,4,5,30],[10,10,20]],[[1,4,5,20],[10,10,30]],[[1,4,5,10,20],[10,30]]
,[[1,4,5,10,20],[10,30]],[[1,4,5,10,10],[20,30]]]
This problem is seen often enough that most Constraint Logic Programming systems include a predicate to model it explicitly. In OPTMODEL and CLP, we call it pack:
proc optmodel;
set SMALL init 1 .. 7, LARGE init 1 .. 2;
num size {SMALL} init [1 5 10 20 30 4 10];
num capacity{LARGE} init [40 50];
var WhichBin {i in SMALL} integer >= 1 <= card(LARGE);
var SpaceUsed{i in LARGE} integer >= 0 <= capacity[i];
con pack( WhichBin, size, SpaceUsed );
solve with clp / findall;
num soli;
set IN{li in LARGE} = {si in SMALL: WhichBin[si].sol[soli] = li};
do soli = 1 .. _nsol_;
put IN[*]=;
end;
quit;
This code produces all the solutions in 0.06 seconds on my laptop:
IN[1]={1,2,3,4,6} IN[2]={5,7}
IN[1]={1,2,3,4} IN[2]={5,6,7}
IN[1]={1,2,3,6,7} IN[2]={4,5}
IN[1]={1,2,5,6} IN[2]={3,4,7}
IN[1]={1,2,5} IN[2]={3,4,6,7}
IN[1]={1,2,4,6,7} IN[2]={3,5}
IN[1]={1,2,4,7} IN[2]={3,5,6}
IN[1]={1,2,4,6} IN[2]={3,5,7}
IN[1]={1,3,4,6} IN[2]={2,5,7}
IN[1]={1,3,4} IN[2]={2,5,6,7}
IN[1]={1,5,6} IN[2]={2,3,4,7}
IN[1]={1,5} IN[2]={2,3,4,6,7}
IN[1]={1,4,6,7} IN[2]={2,3,5}
IN[1]={1,4,7} IN[2]={2,3,5,6}
IN[1]={2,3,4,6} IN[2]={1,5,7}
IN[1]={2,3,4} IN[2]={1,5,6,7}
IN[1]={2,5,6} IN[2]={1,3,4,7}
IN[1]={2,5} IN[2]={1,3,4,6,7}
IN[1]={2,4,6,7} IN[2]={1,3,5}
IN[1]={2,4,7} IN[2]={1,3,5,6}
IN[1]={3,5} IN[2]={1,2,4,6,7}
IN[1]={3,4,7} IN[2]={1,2,5,6}
IN[1]={3,4,6} IN[2]={1,2,5,7}
IN[1]={3,4} IN[2]={1,2,5,6,7}
IN[1]={5,7} IN[2]={1,2,3,4,6}
IN[1]={5,6} IN[2]={1,2,3,4,7}
IN[1]={5} IN[2]={1,2,3,4,6,7}
IN[1]={4,6,7} IN[2]={1,2,3,5}
IN[1]={4,7} IN[2]={1,2,3,5,6}
Just change the first 3 lines to solve for other instances. However, as others have pointed out, this problem is NP-Hard. So it can switch from very fast to very slow suddenly. You could also solve the version where not every small item needs to be assigned to a large bin by creating a dummy large bin with enough capacity to fit the entire collection of small items.
As you can see from the "Details" section in the manual, the algorithms that solve practical problems quickly are not simple, and their implementation details make a big difference. I am unaware of any CLP libraries written in Javascript. Your best bet may be to wrap CLP in a web service and invoke that service from your Javascript code.

Calculating standard deviation not executing loop

I've just started learning coding on code academy and I'm really new to this.
I'm trying to make this program ask the user for values which it adds to an array from which it calculates the sample standard deviation.
// This array stores the values needed
var figures;
getStandardDeviation = function() {
// I need at least two figures for a standard deviation
figures[0] = prompt("Enter a number:");
figures[1] = prompt("Enter a number:");
// Checks whether user wishes to add more values to the array
var confirm = prompt("Would you like to add another? (Y or N)").toUpperCase();
// I can't figure out why the following if statement is not executed
// It checks whether the user wishes to add more values and adds them to the array
// If not it breaks the for loop
if (confirm === "Y"){
for ( i = 0; i === 100; i++){
figures[i + 2] = prompt("Enter a number:");
confirm = prompt("Would you like to add another figure? (Y or N)").toUpperCase();
if (confirm === "N"){
break;
}
}
}
// The rest of the code works fine from here onwards
var sumx = 0;
var n = figures.length;
for(var i = 0 ; i < n ; i++) {
sumx += figures[i];
}
console.log("Sum = " + sumx);
var sumXsq = 0;
for( i = 0 ; i < n ; i++) {
sumXsq += (figures[i] * figures[i]);
}
console.log("Sum x squared = " + sumXsq);
var sxx = (sumXsq - (sumx * sumx)/n);
console.log("Sxx = " + sxx);
var v = sxx/(n - 1);
console.log("Variance = " + v);
var standardDev = Math.sqrt(v);
console.log("Standard Deviation = " + standardDev);
};
getStandardDeviation();
The program is supposed to ask me if I want to add more values to the array, then when I confirm, it gives me a prompt to add more values.
Currently, when I execute the program I input the numbers 56 and 67. The code then asks me if I wish to add more values, I then confirm this. Instead of letting me add more values it ignores this and calculates the standard deviation with the first two values (56 and 67).
The output is:
Sum = 05667
Sum x squared = 7625
Sxx = -16049819.5
Variance = -16049819.5
Standard Deviation = NaN
for ( i = 0; i === 100; i++){[...]} means
Set i to 0
If it's not true that i === 100 (that is: if i is not 100), end the loop
Do whatever I put inside the {} braces, once
Do i++
Back to 2
As the initial value for i is 0 and not 100, the code inside the loop is never executed. If you want it to go from 0 to 99, it should be for ( i = 0; i < 100; i++).
You don't actually need a for loop, though. A while loop would be better. A loop like while (true){[...]} would run until it hit a break statement. As you wouldn't have the i in that case, you could use figures.push(parseFloat(prompt("Enter a number:"))) instead (you should use parseFloat, as per what Vincent Hogendoorn said) . push adds a new value at the end of an array, so it's exactly what you need. Something like:
if (confirm === "Y"){
while (true){
figures.push(parseFloat(prompt("Enter a number:")));
confirm = prompt("Would you like to add another figure? (Y or N)").toUpperCase();
if (confirm === "N"){
break;
}
}
}
You could also change it so it doesn't ask if you want to stop if you don't have at least two values. That way you would be able to leave out that first part:
figures[0] = prompt("Enter a number:");
figures[1] = prompt("Enter a number:");
indeed your figures variable isn't defined as an array, like #James Donnely says.
Keep in mind you also fill in strings, so if you want to add up values you have to convert them to values.
you can use something like parseFloat for this.
if you don't use it, you sum up strings. 3+4 will be 34 instead of 7.
Your figures variable isn't defined as an array. Because of this figure[1] = prompt(...) never gets hit and a TypeError is thrown on var n = figures.length;.
Change:
var figures;
To:
var figures = [];
JSFiddle demo.
You can then replace the for loop you're using after if (confirm === "Y") with a recursive function:
// Push a user input number into the figures array
figures.push(prompt("Enter a number:"));
// Function to add a new number and ask if we want to add more
function addNewNumber() {
// Push a new user input number into the figures array
figures.push(prompt("Enter a number:"));
// Ask if the user wants to add another number
if (confirm("Do you want to add another number?"))
// If they do, call this function again
addNewNumber();
}
// Trigger the function for the first time
addNewNumber();
JSFiddle demo with recursion.
function StandardDeviation(numbersArr) {
//--CALCULATE AVAREGE--
var total = 0;
for(var key in numbersArr)
total += numbersArr[key];
var meanVal = total / numbersArr.length;
//--CALCULATE AVAREGE--
//--CALCULATE STANDARD DEVIATION--
var SDprep = 0;
for(var key in numbersArr)
SDprep += Math.pow((parseFloat(numbersArr[key]) - meanVal),2);
var SDresult = Math.sqrt(SDprep/numbersArr.length);
//--CALCULATE STANDARD DEVIATION--
alert(SDresult);
}
var numbersArr = [10, 11, 12, 13, 14];
StandardDeviation(numbersArr);

Find greatest value in array (in set of integers)

My friend asked me to help him with homework, and I'm stuck. Here is assignment:
user must enter in first prompt box number of elements in array. Then, he will get prompt box for each number to enter. Now, output must be greatest number in array. But that simply doesn't work. With my code below, I always get the element who has greatest first digit. (it's doesn't matter if number is negative or positive, code doesn't work as it should)
Here is my code (it even doesn't work in jsfiddle, just in my file)
<button onclick="duzinaNiza()">Do it!</button>
and here is JavaScript
function duzinaNiza() {
var brClanova = prompt("Enter the number of array elements:");
if (brClanova > 0) {
var niz = new Array();
for (i=0; i<brClanova; i++) {
var redniBr = i+1;
niz[i] = prompt("Enter "+ redniBr +". array number:");
\\ prompt for geting each array element
}
var maximum = niz[0];
for (a=0; a<brClanova; a++) {
if (maximum < niz[a]) {
maximum = niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}
My friend's proffesor doesn't want to use functions for sorting arrays, this must be done with loops.
P.S. Yeah, I know... But don't ask about document.write thing, it must be printed in that way...
That is because the input is a String, you have to parse it to a Integer. Like:
niz[i] = parseInt(prompt("Enter "+ redniBr +". array number:"), 10);
Try this:
function duzinaNiza() {
var brClanova = prompt("Enter the number of array elements:");
if (brClanova > 0) {
var niz = new Array();
for (i=0; i<brClanova; i++) {
var redniBr = i+1;
niz[i] = parseInt(prompt("Enter "+ redniBr +". array number:"));
// prompt for geting each array element
}
var maximum = niz[0];
for (a=0; a<brClanova; a++) {
if (maximum < niz[a]) {
maximum = niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}
The problem is that you are comparing two strings, when you wanted to compare two numbers.
In other words, the following expression is LEGAL in javascript and evaluates to true:
if('4' > '393939393'){
//true! string '4' is greater than string '3' (first char of '393939393')
}
What you should do is cast the value received from the function prompt, so it is treated as a number. You can do that using the following function:
parseInt(prompt("Enter "+ redniBr +". array number:"), 10);
The first parameter is the value you want to cast to a number, while the second is the radix (or "base") of the number.
So, the main problem here is that you're not threat your numbers as "number", but as string. The method prompt returns a string, so you need to convert them:
function duzinaNiza() {
var brClanova = +prompt("Enter the number of array elements:");
if (!brClanova)
return;
var niz = [];
for (var i=0; i < brClanova; i++) {
var redniBr = i + 1;
niz[i] = +prompt("Enter "+ redniBr + ". array number:");
}
var max = niz[0];
for (var a = 1; a < brClanova; a++) {
if (max < niz[a])
max = niz[a];
}
document.write("Greatest value in array is: " + max);
}
I used the Unary Plus Operator for that.
Just for to know, in JS you can actually avoid the last loop using Math.max to get the maximum of an array of numbers. So instead of:
var max = niz[0];
for (var a = 1; a < brClanova; a++) {
if (max < niz[a])
max = niz[a];
}
document.write("Greatest value in array is: " + max);
You will have:
var max = Math.max.apply(null, niz);
document.write("Greatest value in array is: " + max);
In that case, you don't even need the unary plus operator because Math.max takes care of that.
try this out, [Tip: i just utilised the '+' operator for casting the value to number (values from prompt.). The '+' operator will return NaN, if the entered value could not get converted into a number. so in that situation, you should use isNan function to get rid of that.]
duzinaNiza = function () {
var brClanova = prompt("Enter the number of array elements:");
if (brClanova > 0) {
var niz = new Array();
var maximum;
for (i=0; i<brClanova; i++) {
var temp = +prompt("Enter "+ i+1 +". number:");
if(i===0) { maximum = temp }
else { maximum = (temp > maximum)?temp:maximum; }
}
alert("Greatest value in array is: " + maximum);
}
}
You don't need parseInt- if you subtract strings that can be converted to numbers, they are converted. So you can subtract the maximum from the next number, and see if it leaves a remainder.
Also, parseInt will destroy decimals, so you won't know that 1.5 is greater than 1.
Your comment used the wrong characters- `('\' should be '//')
function duzinaNiza(){
var brClanova= prompt("Enter the number of array elements:");
if(brClanova>0){
var niz= new Array();
for(var i= 0;i<brClanova;i++){
var redniBr= i+1;
niz[i]= prompt("Enter "+ redniBr +". array number:");
//prompt for geting each array element
}
var maximum= niz[0];
for(var a= 0;a<brClanova;a++){
if(niz[a]-maximum>0){
maximum= niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}
Modified Code JSFIDDLE
function duzinaNiza() {
var brClanova = prompt("Enter the number of array elements:")*1; //convert string to intger
if (brClanova > 0) {
var niz = new Array();
for (i=0; i<brClanova; i++) {
var redniBr = i+1;
niz[i] = prompt("Enter "+ redniBr +". array number:")*1;
// prompt for geting each array element
}
var maximum = niz[0];
for (a=0; a<brClanova; a++) {
if (maximum < niz[a]) {
maximum = niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}

Categories