Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Can somebody please explain how this code gets which number from array is the biggest?
var num = [];
for( var i = 0; i < 10; i++ ) {
num[i] = parseInt( prompt("Unesite broj " + (i+1) + "." ) );
}
var biggest = 0;
for(i=0; i < num.length; i++ ) {
if( num[i] > biggest ) {
biggest = num[i];
}
}
console.log("The biggest number is " + biggest );
To start, we've seen no numbers, and the code assumest the biggest is 0 or larger:
var biggest = 0;
We'll look at each number in the list:
for(i=0; i < num.length; i++ ) {
Is the current number bigger than the biggest we've seen?
if( num[i] > biggest ) {
If so, it's the new biggest number
biggest = num[i];
}
}
When the loop is done, biggest contains the largest number we saw along the way.
First for loop just prompts you to add numbers to an array.
The second loop just checks each number in the num array, if that number is bigger than the number in the biggest variable then it sets the biggest variable to that number.
It's as simple as that.
The if statement within the loop checks whether the number in the current element of the array is greater than the largest number found so far. If the current number is the greatest, the largest number found so far is updated to this new number.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 12 months ago.
Improve this question
Sorry, I dont know anything about programming, so bare with me.
I need an expression for a textlayer in adobe after effects which uses javascript. The expression needs to create a customizable list of numbers using 3 variables -
example:
x = 0 //starting point (the first number in the list)
y= 20 //increments (the size of the steps)
z= 5 //the number of steps
the output needs to be a list with each entry in a new line, in this case:
0
20
40
60
80
Hope somebody can help. Thanks
x = 0 //starting point (the first number in the list)
y= 20 //increments (the size of the steps)
z= 5 //the number of steps
let output=[]
for(let i=x;i<z;i++){
console.log(i*y)
output.push(i*y)
}
console.log(output)
let arr = [];
let x = 0;
let y = 20;
let z = 5;
for (let i = 0; i < z * y; i+= y) {
arr.push(i);
}
console.log(arr);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
The example string(s) can look like that:
"3.0000+3"
"3.00+3.00"
"3.00+3.000"
I want to find the highest amount of decimal places out of the numbers inside 1 string
The most straight-forward way to do this is iterating over the string, checking for the occurence of a dot and from there on count the number of digits up to the next character that's NOT a number or the end of the string. Since your string contains multiple numbers you need to add a variable which holds the highest amount of decimal places.
e.g.
var str = "3.00+3.000";
function getDecimalPlaces(numb) {
var highest = 0;
var counter = 0;
for (a = 0; a < numb.length; a++) {
if (numb.charAt(a - 1) == ".") {
do {
counter++;
a++;
}
while (!isNaN(numb.charAt(a)) && a < numb.length);
}
if (counter > highest) {
highest = counter;
}
counter = 0;
}
return highest;
}
console.log(str + " has " + getDecimalPlaces(str) + " decimal places");
This can be made a bit more elegant by using a regular expression in conjunction with the .match() method. This searches a string for a given pattern and returns an array of results.
var str = "3.00+3.000";
console.log(str.match(/(\.)([0-9]+)/g));
This will return an array like:
[".00", ".000"]
By comparing the length of it's elements - minus 1 since it includes the dot - we can get the number of decimal places using this nifty short function:
var str = "3.00+3.000";
var highest = str.match(/(\.)([0-9]+)/g).reduce(function(a, b) {
return Math.max(a.length - 1, b.length - 1);
});
console.log(str + " has " + highest + " decimal places");
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I was at internship interview, where I couldn't solve one logical exercise. It was too complicate for me. Could you help me and explain how to solve it? (I didn't pass, but I really want to know how to solve it). Exercise is:
"Given an array arr of strings complete the function landPerimeter by calculating the total perimeter of all the islands. Each piece of land will be marked with 'X' while the water fields are represented as 'O'. Consider each tile being a perfect 1 x 1 piece of land. Some examples for better visualization:
['XOOXO',
'XOOXO',
'OOOXO',
'XXOXO',
'OXOOO']
see image here : https://i.ibb.co/pbDwWSs/pic1.jpg
should return: "Total land perimeter: 24",
while
['XOOO',
'XOXO',
'XOXO',
'OOXX',
'OOOO']
see image here: https://i.ibb.co/Pcdy8Ct/pic2.jpg
should return: "Total land perimeter: 18"
Kindly ask you to show code example how could I solve this exercise.
Thank you very much!
please see this link find-perimeter-shapes-formed-1s-binary-matrix. need some small modifications in your case . see below
<script>
function numOfNeighbour( mat, i, j,rows,cols)
{
var count = 0;
// UP
if (i > 0 && mat[i - 1][j]==='X')
count++;
// LEFT
if (j > 0 && mat[i][j - 1]==='X')
count++;
// DOWN
if (i < rows-1 && mat[i + 1][j]==='X')
count++;
// RIGHT
if (j < cols-1 && mat[i][j + 1]==='X')
count++;
return count;
}
function findPerimeter( mat)
{
var perimeter = 0;
var rows=mat.length;
var cols=mat[0].length;
// Traversing the matrix and finding ones to
// calculate their contribution.
for (var i = 0; i < rows; i++)
for (var j = 0; j < cols; j++)
if (mat[i][j] && mat[i][j]==='X')
perimeter += (4 - numOfNeighbour(mat, i ,j,rows,cols));
return perimeter;
}
console.log("perimeter of ['XOOXO', 'XOOXO', 'OOOXO', 'XXOXO', 'OXOOO'] is ",findPerimeter(['XOOXO', 'XOOXO', 'OOOXO', 'XXOXO', 'OXOOO'])); //24
console.log("perimeter of ['XOOO', 'XOXO', 'XOXO', 'OOXX', 'OOOO'] is " ,findPerimeter(['XOOO', 'XOXO', 'XOXO', 'OOXX', 'OOOO'])); //18
</script>
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm having a php json_encode object fetched by ajax. whet I want to do is to sum this array. Here's what I did so far:
var json = $.parseJSON(data);
var tot = new Array();
for (var i = 0; i < json.length; ++i) {
tot.push(json[i].final_total);
$('table tbody').append("<tr><td>" + json[i].order_id + "</td><td>" + json[i].final_total + "</td></tr>");
}
Now I want to sum this array. I tried this:
var sum = tot.reduce(function(pv, cv) { return pv + cv; }, 0);
$("#total").html( sum );
But the result is:
09.748.529.129.129.119.59.79.89.79.89.79.79.79.79.79.79719.248.59.79 ......
I also tried:
myFunction(tot);
function getSum(total, num) {
return total + num;
}
function myFunction(item) {
document.getElementById("total").innerHTML = item.reduce(getSum);
}
But I got the same result above (Numbers written next to each other).
I also tried this:
var tot = 0;
for (var i = 0; i < json.length; ++i) {
tot += json[i].final_total);
$('table tbody').append("<tr><td>" + json[i].order_id + "</td><td>" + json[i].final_total + "</td></tr>");
}
$("#total").html( tot );
But I got the same result above (Numbers written next to each other).
So what is the proper way to sum an array in javascript?
You have to use parseInt (if the numbers are Integers), parseFloat (if they are Floats) or Number (if not sure) to explicitly interpret them as numbers like:
sum = tot.reduce((a, n) => (a + Number(n)), 0);
Array elements are strings, in order to properly add them, they have to be casted to integer:
var sum = tot.reduce(function(a, b) {
return parseFloat(a) + parseFloat(b);
}, 0);
Taken from MDN:
the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.
The is a common issue caused by + operator used for both string concatenation and addition. Issue is best described with following example:
var result = '1' + 3 + 3 + 7 //result is '1337'
Edit: #Pointy - Nice catch, thanks! :)
you will need to use a parse int because its concatenating the sting instead of adding integers
var sum = tot.reduce(function(pv, cv) { return parseInt(pv) + parseInt(cv); }, 0);
parseInt
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I need to know the code built in for the syntax math.pow(x,y). Actually I used the syntax to find exponent of any number... e.g.
var e = Math.pow(-3, 3); yields -27 but couldn't find out the program behind this... Help me please
If you know what power means..
multiplying the number x n times where x is base and n is exponent.
So you just have to repeat the same thing over and over - and that's why loops are for:
var sum = 1; //note that it's not zero!
for (int i=0;i<n;i++) { //loops n times
sum = sum * x; //on each loop multiplies sum by base number
}
Did you mean alternative for Math.pow? Here is one way with simple loop.
function pow(base,power) {
var p = 1;
for (var i=0; i<power; i++) {
p *= base;
}
return p;
}
You can also use recursion to solve this kind of challenge. Beware that recursion has the disadvantage of increasing space complexity as compared to a for-loop.
function pow(base, power) {
if (power === 1) return base * power
return base * pow(base, power - 1)
}
This is a better way to calculate power of a number with recursion:
function power(base, exp) {
if(exp === 0){
return 1;
}
return base * power(base, exp - 1);
}
You can try this:
function pow(n, e) {
let num = n;
for (let i = 1; i < e; i++) {
num *= n;
}
return num;
}
console.log(pow(-3, 3));
It will give you the required result.