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
I am writing a program that determines if a number is between two values in an array.
Here is an example of the array I am using.
var attackArray = new Array (2);
attackArray[0] = new Array("0","1","2","2","2","3","4");
attackArray[1] = new Array("2","3","2","3","2","3","4");
I am using the following code to compare the number against the first two values in the array. I then loop through the array until I find a line that meets the requirements. The number must be >= to the first number and <= the second number.
Here is the code that I am using.
function leveltest ( number)
{
var attack = attackArray.length;
for ( var count = 0 ; count < attack; count ++)
{
if ((number >= Number(attackArray [count][0])) && (number <= Number(attackArray [count][1])))
{
do something ;
}
}
}
If someone can look at my code and explain what I am doing wrong.
I believe you are trying to compare a number to each range of numbers defined by the item values with the same index in element 0 and element 1 of attackArray. If that is right, then the following applies.
The problems present in your code snippet were:
You have the index wrong on line 3. Your third line, attackArray[2] = new Array("1","3","2","3","2","3","4"); is creating a new third element in the attackArray created on the first line. Instead, I think you are wanting to populate the second element of attackArray which should be attackArray[1] = new Array("1","3","2","3","2","3","4"); Or you could use different array syntax as shown below.
In the function, you were using the length of attackArray var attack = attackArray.length;, to control the for loop following. Instead, you will want, var attack = attackArray[0].length; so long as attackArray[0] and attackArray[1] are the same length. You can think of it like this, you were getting your length along the wrong dimension of your array. You were getting the length "down" your array or list of objects, ran than "across" the horizontal dim of your array.
In the function, you are confused on how to loop through the array, and you have this attackArray [count][0] and attackArray [count][1] backwards. Instead they should be attackArray[0][count] and attackArray[1][count]. This will allow you to properly compare your number with each item in element 0 and the item of the same index in element 1.
The following code should be a concise, correct working piece of code to accomplish your goal. You can take and plug this in to jsfiddle.net and it should work in Chrome with the Javascript console used to view the results in the log. Here it is:
var attackArray = [];
attackArray[0] = ["0","0","2","2","2","3","4"];
attackArray[1] = ["1","3","2","3","2","3","4"];
function leveltest (number){
var attack = attackArray[0].length;
for (var count = 0;count < attack;count ++){
if ((number >= Number(attackArray [0][count])) &&
(number <= Number(attackArray [1][count]))) {
console.log(number + " matches at index " + count);
}
}
}
leveltest(2);
Looks like your second element in attackArray has the wrong index.
attackArray[2] = new Array("1","3","2","3","2","3","4");
attackArray.length == 2
you "count" can go up to 1, attackArray[1] is not defined by you.
The second comparation inside the if is wrong. At the second loop it will be attackArray[1][1] and you created an attackArray[0] and attackArray[2].
Related
I am a "new" developer into the foray of Web Development and I have come across an issue I was hoping that you fine people on Stack Overflow would be able to help me with. I have asked several Cadre and Instructors in my class and we are all stumped by it.
To start with I have decided to put all of my code on a Gitlab repo so if you want to look at the whole thing (or if you want to add to it let me know): Link to Github Repo. I fiqured you guys don't want the whole thing posted as a wall of text and rather some snip-its of what in the file I specifically. But it is relitively small file
I am useing simple JavaScript as well as Node.Js to be able to build a working calculator in the back end that I can use as a template for any other project I will need to work on in the future. For now I am trying to just get it working by imputing things via the console.
I have made a way for what is imputed in Node and to an imputArray var I have set up and the Array goes something like this:
[(command), (num1), (num2), (num3), ...]
I set up a switch function that runs a block of code based on what command was given (add, subtract, divide, etc..). As well as separating the command from the number and putting them inside another array.
The part I need some help with is with getting the block of code to work for what I want it to do. I have got it set up to run rather easily on two numbers but I want it to handle as many numbers as I want to throw at it. I tried various forms of for loops as well as forEach loops and I cant seem to get it working.
case 'divide':
for (i = 1; i < numArray.length; i++) { // If any number besides the first is 0 spit out this
if (numArray[i] === 0) {
consol.log("You canot divide by zero!");
}
else {
var previousTotal = numArray[0]; //Inital number in array
for (i = 1; i < numArray.length; i++) {
previousTotal = previousTotal / numArray[i]; // for each number in array divide to the previous number
}
}
result = previousTotal // Pushes end total to result
}
break;
I have gone through several different versions of the above code (such as using for loops instead) but this is pretty much what I ended up with. I'm sure there is an easier way and more sane way to do what I am trying to do, but if I knew how I wouldn't be here.
Essentially this is the ideal thing I want to do but I cant find a way to do it: I want to run a small block of code the index of the number array, minus one. In this case it is dividing the previous number by the next number in the array.
So it only runs if there are more then one in the array and it does the function to the previous number, or total from the last one in the array.
This is pretty much the only thing holding me back from finishing this so if someone can take the time to look at my crapy code and help it do what I want it to do that would be awesome.
Your code is reseting result each time the outer loop iterates so it will just equal what ever the last prev Total is. Basically every loop but the last is irrelevant. Do you want to add them to result? If so you want:
result += previousTotal
Or if you want an array of the answers you want:
result.push(reviousTotal)
Sorry not 100% what you want. Hope this helps!
You just need one loop, and you probably want to stop iterating if a 0 occurs:
result = numArray[0]; //no need for another variable
for (var i = 1; i < numArray.length; i++) { // declare variables!
if (numArray[i] === 0) {
console.log("You canot divide by zero!"); // typo...
break; // exit early
}
result = result / numArray[i];
}
For sure that can be also written a bit more elegantly:
const result = numArray.reduce((a, b) => a / b);
if(isNaN(result)) {
console.log("Can't divide by zero!");
} else {
console.log(`Result is ${result}`);
}
I assume you want the divide command to do ((num1/num2)/num3)/...
There are couple of issues in the code you posted, I will post a version that does the above. You can inspect and compare it your version to find your mistakes.
// divide, 10, 2, 5
case 'divide':
if (numArray.length < 2) {
console.log("no numbers in array")
break;
}
// previousTotal starts with 10
var previousTotal = numArray[1];
// start from the second number which is 2
for (i = 2; i < numArray.length; i++) {
if (numArray[i] === 0) {
console.log("You canot divide by zero!");
}
else {
previousTotal = previousTotal / numArray[i]; // for each number in array divide to the previous number
}
}
result = previousTotal;
// result will be (10/2)/5 = 1
break;
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
I'm trying to map the maximal amount of days without rain using the TRMM dataset in Google Earth Engine. I'm doing this by iterating over the collection and if no rain has fallen, one gets added to the cell (code below). When rain has fallen the value gets multiplied by 0 so the "counter" is reset. Then I would like to store each result of each iteration in a Image collection and then select the maximum value to get the longest consecutive dry period.
But that is the theory. When I put this in a script I get an error while adding the image of one iteration to a list. Does anyone know why this is and how this can be solved?
Code:
var list = [];
function drylength(current, previous){
var mask = current.remap([0], [1], 0,"precipitation").rename('precipitation');
var sum = mask.add(previous).multiply(mask);
list.push(sum);
return sum;
}
var dataset = TRMM
.filterDate("2015-01-01","2015-02-01")
.sort('system:time_start:');
var totalPrecipitation = dataset.iterate(drylength, dataset.max()
.remap([0], [0], 0, "precipitation")
.rename('precipitation'));
print(list);
print(totalPrecipitation);
Map.addLayer(ee.Image(totalPrecipitation), imageVisParam);
Furthermore it appears only 3 items are stored in the list which makes me assume the iteration is more complex than a literal iteration where all images are calculated one by one? Here is an image of the error:
Errors written if image is not visible or for search engines:
Failed to decode JSON.
Error: Field 'value' of object '{"type":"ArgumentRef","value":null}' is missing or null.
Object: {"type":"ArgumentRef","value":null}.
and:
Unknown variable references: [_MAPPING_VAR_0_0, _MAPPING_VAR_0_1].
Something like this to use a multi-value result:
function drylength(current, previous) {
previous = ee.Dictionary(previous)
var mask = current.remap([0], [1], 0,"precipitation").rename('precipitation');
var sum = mask.add(previous.get('sum')).multiply(mask);
var list = previous.get('list')
list = list.push(sum);
return ee.Dictionary({sum: sum, list: list})
}
...
var totalPrecipitation = dataset.iterate(drylength, {sum: max, list: ee.List([])})
The iterate() function runs on the server, but the list you're attempting to push into is a client-side list; that can't work. If you make it an ee.List, you might be able to get it to work, but you'll have to put it into the previous result (use previous as a dictionary to hold both).
I would like to sort a news feed according to created date, which is trivial, but I don't want 2 consecutive posts with the same userId field.
This might not be theoritically possible because what if I have only 2 posts with the same userId field?
I am looking for an algorithm that sorts according to fieldA but doesn't have 2 consecutive elements with the same fieldB.
It would also nice to have a parametrized algorithm about the required number of different posts between same user's different posts. (In the first scenario this parameter is 1)
I'm not looking for performance (O(n^2) would be okay) but a clever & simple way, maybe with 5 lines of code.
Language doesn't matter but Javascript is preferred.
To solve this problem in 5 lines is somewhat difficult,I'm trying to give a short pseudocode and you may translate it to js.
First we group the input to A[1],A[2],...,A[k].A[i] is a container contains all posts of i-th user,this can be easily done via O(n) scanning.
code:
for i = 1 to k
lastOccurPosition[i] = -intervalLength; //that is the interval length specified by parameter
for i = 1 to k
sort(A[i]);
for i = 1 to n
minElement = INF; //find the minimum
minUserId = -1; //record whose post is minimun
for j = 1 to k
if(i - lastOccurPosition[i] <= intervalLength) //if the user has occured within interval length,the user's post shouldn't be choosen
continue;
if(A[j][1] < minElement)
minElement = A[j][1];
minUserId = j;
answer[i] = minElement; //put min element into answer array
lastOccurPosition[minUserId] = i; //update choosen user's last occur position
A[minUserId].pop_front(); //delele first element
It is easy to analyse this algorithm's complexity is O(n^2) and I haven't thought out a more concise solution.
Hope to be helpful.
Put the atributes in an array, and sort that array:
arr.sort();
Put the second atribute in another array and sort that array according to the first one.
var newarr = [arr[0]];
for (var i=1; i<arr.length; i++) {
if (arr[i]!=arr[i-1]) newarr.push(arr[i]);
}
Now this just remove duplicates.
This all feels kind of trivial, am I missing something?
Hope this helps.
Cheers,
Gijs
This question already has answers here:
Javascript looping through Fibonacci numbers and testing for even numbers
(2 answers)
Closed 8 years ago.
I am new to JavaScript and am having trouble getting my code to work. Any help/guidance is greatly appreciated.
I am getting the wrong output (currently “9.715575428267785e+30“) when trying to “displays the sum of first 50 even Fibonacci numbers”
I needed to:
1. create a loop that generates Fibonacci numbers.
2. test each one for whether it's even or odd.
3. Add up up the even ones, counting them as you go.
------------HERE IS MY CODE THUS FAR --------
<div id="sumFib" class="hwbutton">Get the Sum!</div>
The sum of the first 50 even Fibonacci numbers is:
<span class="" id="sumFibResult"></span>
<script>
var getFibSum = document.getElementById("sumFib");
getFibSum.onclick = function () {
fiftyEvenFibonacciSum();
}
function fiftyEvenFibonacciSum() {
var loopFib;
//Initialize fibonacci array
var fibonacci = new Array();
//Add fibonacci array items
fibonacci[0] = 0;
fibonacci[1] = 1;
var sum = 0;
//Since it takes 150 fib numbers to obtain 50 even, loop through that many.
for (loopFib = 2; loopFib <= 150; loopFib++) {
// Next fibonacci number = previous + one before previous
fibonacci[loopFib] = fibonacci[loopFib - 2] + fibonacci[loopFib - 1];
//test for even numbers with if then statement
var integer = parseInt(fibonacci[loopFib]);
if (integer % 2 == 0) {
//Add up the even fib numbers if even and output into dispay variable
var display = sum += fibonacci[loopFib];
//output results to html page
document.getElementById("sumFibResult").innerHTML = display;
}
}
}
</script>
http://jsfiddle.net/isherwood/38gPs
I disagree with the people saying this is a duplicate because I think the real question you are asking is "how do I debug my failing program?" I am sure that must be a duplicate too but, well, hem...
Anyhow I think what would help you a lot here is console.log(). I don't know what browser you are using but all major ones have a JS console. (I recommend Firefox with Firebug.) Add lines like:
console.log('integer for ' + loopFib + '=' + integer);
Or
console.log('display=' + display);
To the relevant points in your script. Then open your browser's JavaScript console to view the results. I already see some major boners in your code but I'm not going to correct them for you - this is your homework assignment after all and I'd rather teach a man to fish. Comment on this reply if you have any more questions.
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 9 years ago.
Improve this question
SOLVED
From a previous post I did and with the help of some suggestions I have managed to write a function that technically should be doing what I required it to. However the results are not entirely correct.
I have tried to add markup to the JS to explain what is going on, but to explain I have div's like follows:
<div class="section-link">
<div class="price"> £59.99</div>
</div>
<div class="section-link">
<div class="price"> £259.99</div>
</div>
I am trying to have the function hide all these div's and only show the ones if the price is within the given price range.
The data I am passing into the function is: £0.01 - £59.99 or £60.00 - £159.99 or £160.00 - £500.00
from using alert's everything is working fine, however when it gets to the if statement for the filter it is not filtering how it should be.
Any help appreciated
The js:
function price(string){ // passing in the strings as £0.01 - £59.99 and £60.00 - £159.99 etc
$('.section-link').hide(); // hide all section-link div's'
var range = string.replace(/\u00A3/g, ''); // strip pound sign's from range
var rangearray = range.split("-"); // split into 2 value arrays
lowarray = rangearray[0].toString(); // get low value as string
higharray = rangearray[1].toString(); // get high value as string
lowvalue = lowarray.replace(/ /g,''); // strip spaces
highvalue = higharray.replace(/ /g,''); // strip spaces
alert(lowvalue); // testing low value string (is alerting right) - 0.01
alert(highvalue); // testing high value string (is alerting right) - 59.99
$(".price").filter(function(){ //do a filter for all div's with the class of price
var divprice = $(this).text().replace(/\u00A3/g, ''); // strip pound sign from price value
var maindivprice = divprice.replace(/ /g,''); // strip spaces from price value
if (maindivprice >= lowvalue && maindivprice <= highvalue) {
alert(maindivprice); // alerting to see what prices it is saying are between the range (these are showing all the prices and not only ones between the range)
$(this).parent().show(); // show this parents div
} // filter to see if this price is in the price range
});
}
Is it possibly something to do with the decimal points?
Try using parseFloat on your number variable, if this was a string then it is trying to compare a string value to a float value
lowvalue = parseFloat(lowarray.replace(/ /g,'')); // strip spaces
highvalue = parseFloat(higharray.replace(/ /g,'')); // strip spaces
var maindivprice = parseFloat(divprice.replace(/ /g,'')); // strip spaces from price value