I am going nuts trying to write a JavaScript code, which requests from the user any sequence of numbers until such user enters 'N'.
If this happens, a message should pop up indicating the user that he reached the end of that sequence and then a new message pops up showing 'all' the numbers the user entered PLUS organising them in crescent order.
Any suggestions, please?
I would appreciate any help as I'm going mad right now thinking of anything.
If the array was specified, then I wouldn't have a problem, but since it's a random array, I can not seem to find the right answer.
What you want to do is something like this:
Get the user's numbers and save them, prefably in an array.
Loop through all the numbers and check if the number is N.
If so, alert the user.
Sort the array, alert the user.
Attempt to code:
// All the user's numbers
var UserNumbers = [15, 10, 11, 12, 13];
//The value to search for
var N = 12;
//Loop through the values
for(var i = 0; i < UserNumbers.Length; i++){
if(UserNumbers[i] == N){
//The number matches
alert("You reached the end of the sequence";
}
}
// I am not sure what you mean with cresent order so that you'll have to solve for yourself.
//Sort the UserNumbers here
//Store the message to show the user
var message = "";
//Loop through the values - now in correct order and save them to the message
for(var i = 0; i < UserNumbers.Length; i++){
//Add to the message
message += UserNumbers[i] + " ";
}
//Show the message - all the containing numbers
alert(message);
Although this is an helpful community I am pretty certain that we're not made out of teachers here to teach you how to code. Since this sounds to be an homework rather than a real life scenario, talk with your teacher or classmates. Good luck and next time, try to do some research before posting a question - there are plenty of tutorials for beginners out there.
Related
Idea for making elements visible or invisible:
So… how the loop works right now is it for each category, it loops through each question in each category.
The idea is: Each question can be answered yes or no, and then for each question answered yes, there can be up to 5 dates added.
What I want to do:
-If yes, first date appears:
-If the first date is answered, then a second question appears, and so on.
These questions are stored in a sql server like so:
I want only the inner loop to have this ability to be visible or invisible..
My thought is to do a nested loop and check check on each element.
//Psuedo code
//For each first question which has 5 sub questions that are all set to hidden:
var questioncount = (count of the first questions)
for(int i = 0; i<questioncount; i++){
// set first variable to hold the first questions object.
var element(‘#questionElement’ + i);
// set firstElement to selected answer
var isAnsweredYes = firstElement.(‘Yes’);
for int j = 0; i<subQuestionCount; j++)
if (isAnsweredYes == True){
// jQuery selector to get an element
var query = $('#element' + j);
// check if element is Visible
var isVisible = query.is(':visible');
if (isVisible === true) {
// element is Visible
// do nothing
} else {
// element is Hidden
query.show();
}
else
{
//do nothing
}
}
}
Does my logic seem forward? or can anyone advise me in a better way?
I would use a button that says "Add another date", which is displayed under the last date field as soon as at least one is visible. That way you won't have to decide on a certain number (e.g. 5) as the maximum, plus I think it's a rather intuitive way of extending a form.
On each press of the button, create new input controls; be it in javascript or server side, it makes no real difference.
I have looked everywhere I can think of for anything that can provide an answer to this. First time posting a question here - I can usually find my answers. I have a for loop that is pulling information from a range of data that is formatted in one cell like this: 09/01/2016 - Status changed to active.
The loop is supposed to first see how many values are in that column then go one by one and split the data into a simple array, post it into two columns on a separate sheet, then move onto the next one. The problem is that it stops after the first entry.
var numEntries = dataSheet.getRange(1,i+1,1000).getValues();
var lastEntry = numEntries.filter(String).length;
if (lastEntry == 7) {
// no change data to date
sheet.getRange(18,3).setValue("No changes yet");
} else {
var changeData = dataSheet.getRange(8,i+1,lastEntry-7).getValues();
for (var y = 0; y < changeData.length; y++) {
var changeHistory = changeData[y][y].split(" - ");
sheet.getRange(nextRow+1,2).setValue(changeHistory[0]);
sheet.getRange(nextRow+1,3).setValue(changeHistory[1]);
nextRow++;
Logger.log(nextRow);
Logger.log(changeData.length);
Logger.log(y);
}
}
I know that it is executing properly because it is properly setting the "No changes yet" value when there are no entries. Variable nextRow starts at a value of 17, and the log properly shows changeData.length with the number of entries and y being equal to 0. But then it stops. It doesn't follow the loop that y is still less than changeData.length. Any help is very much appreciated!
[edit] - I also want to point out that it does properly split and populate the first value into the two cells I want it to, so the whole for statement does work, it just doesn't loop. [edit]
[16-09-29 15:37:48:514 CDT] 18.0 [16-09-29 15:37:48:515 CDT]
11.0 [16-09-29 15:37:48:515 CDT] 0.0
changeData is an n*1 Array.
You are increasing y and and you are also trying to get the y-th column from changeData.
After the first iteration this is undefined because there's only one column.
undefined does not have a split method throwing an exception and terminating the script. (You may not see this exception, these kinds of exceptions aren't always shown to the user for some reason)
Try
var changeHistory = changeData[y][0].split(" - ");
instead.
https://jsfiddle.net/andrew_jsfiddle/eyLyqajz/1/
Assignment 1 - Using your JSFiddle account you are going to create a guessing game, only it will be the computer doing the guessing. Here is how it works - the computer will ask you for a number between 1 and 1000, it will check first to make sure your input is within the bounds.
Once you enter the number it will guess the number and do a comparison with the number you entered. It will output the results of the guess and continue to do this until it gets the correct answer. This is what the output of the program will look like (if I enter 329)
For this attempt I did:
var guessnum= new Guessnum(1000);
document.getElementById("click").onclick= function() {
guesslist()};
function guesslist() {
document.getElementById('guessnum').innerHTML= InsertGuess();
}
function InsertGuess() {
for (var a= 0; a < guessnum.length; a++){
guessnum[a] = Math.floor((Math.random() * 1000) + 1);
}
var show_guess="";
for (i=0; i < guessnum.length; i++){
show_array += "You guess" + guessnum[i] + "of " + i + "<br>";
}
return document.getElementById('guess').innerHTML=show_array;
}
Use a listener on the input with a global variable that contains the random number
var myRandomNumber;
input.addEventListener('input', function(){
}
)
You'll need to click first on the button though.
Fiddle
My friend, I think you are really confused. It wouldn't help to just create it for you. Break down the requirements to actionable steps and start from scratch. You want to create a guess game that you set a number. Think it as simply as possible:
Action 1 - Set a number -->
Create the field
Action 2 - Check if number is valid(1-1000) -->
Get the value entered and make the necessary checks
Action 3 - Computer tries to guess by selecting a num up to 1000 -->
Generate random num from 1-1000
Action 4 - Compare number with the one you set before -->
Simple comparison of generated number and the selected one
Action 5 - Proceed as needed -->
If it's the exact number it won and it will stop!
If it's higher then the next guesses should have this number as highest limit.
If it's lower then the next guesses should have this number as lowest limit.
Action 6 - Show guess and result of comparison --> Simply show the results of the previous actions
Action 7 - If not successful guess --> repeat until the number is guessed
Try to apply this kind of logic to all these problems.
Update:
The story is off-topic and the title misleading. The problem is caused by corrupted data set, not cursors, or MongoDB itself. But I would rather like to leave this thread here than to delete it, for that it might help other desperate people.
=== Original story starts here ===
It all starts here: MongoDB: cannot use a cursor to iterate through all the data
I was trying to iterate through a cursor in Java, and it fails because my collection has too many records(~250M). I tried to allocate a new cursor and use cursor.skip to jump back in when the cursor gets timed out but cursor.skip itself times out.
#mnemosyn pointed out the right way for me: break the job into two stages: In the first stage, use a projected cursor to pull only the monotonic _id's of the records. Record the _id's, and then store it somewhere else as "checkpoints". During the second stage, I can then access any chunk of records as a checkpoint recorded.
So I wrote a javascript like this:
db=connect("localhost/twitter");
db.jobScheduler.drop();
for(var i = 0;i<16;++i)
{
db.jobScheduler.save({_id:"s"+i,jobs:[]});
}
var c = db.tweets.find({},{_id:1}).sort({_id:1});
var totalCount = c.count();
var currentBatchSize = 0;
var currentNum = 0;
var currentShard = 0;
var startTid = 0;
var endTid = 0;
var currentTid = 0;
while(true)
{
while(c.hasNext())
{
var doc = c.next()
currentTid = doc._id;
if(currentBatchSize == 0)
{
startTid = doc._id;
}
++currentNum;
++currentBatchSize;
if(currentBatchSize == 50000)
{
currentBatchSize = 0;
endTid = doc._id;
db.jobScheduler.update(
{_id:"s"+currentShard},
{$push:{jobs:[startTid,endTid]}});
currentShard = (currentShard+1)%16;
print(currentNum+"/"+totalCount+"("+currentNum*100/totalCount+"%)");
print("["+startTid+","+endTid+"]");
}
}
if(currentNum != totalCount){
var c = db.tweets.find({_id:{$gt:currentTid}},{_id:1}).sort({_id:1});
print("Cursor resetted....");
}else
break;
}
if(currentBatchSize != 0)
{
currentBatchSize = 0;
endTid = doc._id;
db.jobScheduler.update(
{_id:"s"+currentShard},
{$push:{jobs:[startTid,endTid]}});
currentShard = (currentShard+1)%16;
}
Considering that simply pulling _id only would still result in timeout, I added a guard like this:
if(currentNum != totalCount){
var c = db.tweets.find({_id:{$gt:currentTid}},{_id:1}).sort({_id:1});
print("Cursor resetted....");
}else
break;
because when the cursor times out, I don't get an exception but a false cursor.hasNext().
Since I already recorded currentTid when iterating through them, using the range query var c = db.tweets.find({_id:{$gt:currentTid}},{_id:1}).sort({_id:1}); will put me back in position, theoretically. However the poor little program end up like this:
[337242463750201340,345999466677010400]
21800000/253531208(8.598546968624076%)
[345999469818544100,346244305876295700]
Cursor resetted....
Cursor resetted....
Cursor resetted....
It seems to be stuck at the first occurrence of cursor timeout, forever. And the range query is not bringing me back.
Now I'm really confused. Iteration doesn't work. cursor.skip() doesn't work. Range query doesn't work. And what really works with MongoDB? Or is there something I'm doing really wrong?
Any help would be much appreciated!
Update:
I had some discussion with #AsyaKamsky, he helped me to discover the following things:
setting cursor.batchSize() to 10 doesn't work.
The behaviour is not caused by an idle cursor waiting for 10 minutes. The cursor is pulling data rapidly from server, but still gets invalidated.
The real problem is that after it gets invalid in this way, I could never reallocate any usable cursors anymore. All the new cursors refuse to give me data. There is one possible workaround: close the cursor before this happens, and re-allocate one and use range query to jump back.
Experiments ongoing. Updating this thread in real-time :-)
Update: Failed! I tried renewing cursor after reading 50k records every time. It also gets trapped at this magical index 21800000! That's very close to my cursor.skip() failure offset!
Update:
Confirmed the guessing:
c = db.tweets.find().skip(21800000); //works
c = db.tweets.find().skip(21850000); //doesn't work
I'll try binary search on this range to find the magic number.
Update:
Ok... Magic number found.
db.tweets.find().itcount()
->21837006
db.tweets.find().count()
->253531208
Now what? This is really bad.
I need to take a textbox that is full of formatted info about accounts and then sort it somehow. I would like to know if it would be ideal (I'm trying to make this as efficient as possible) to parse the info into a two dimensional array, or if I should make account objects that will hold info in fields.
The program is simply meant to format the data so that it can be printed out without having to copy/paste.
So far I have...
function generateOutputfvoc()
{
var accountLines = document.getElementById('accountLines').value;
var accountLinesTemp = accountLines.split(/[\s]/);
for(var i = 0; i < accountLinesTemp.length; i++)
{
if(accountLinesTemp[i].match(/
Edit (1-18-13): Here is an example input. It is basically text copied from a web CRM tool. Note, this example input is something I typed up randomly.
P8B000001234567 stackoverflow Thing 12522225555 444 Active 2005-02-26 CO1000123456
P8B000001234568 stackoverflow Another Thing 444 Active 2005-02-26 CO1000123456
P8B000001234569 stackoverflow Another Thing 556 Active 2005-02-26 CO1000123456
I would like my program to take the text and simply output the text like this:
P8B000001234567 stackoverflow Thing 12522225555 444 Active 2005-02-26 CO1000123456
P8B000001234568 stackoverflow Another Thing 444 Active 2005-02-26 CO1000123456
P8B000001234569 stackoverflow Another Thing 556 Active 2005-02-26 CO1000123456
Also, I would like to know if I should use jQuery variables. I asked this because I have been looking online a lot and I found examples that use code that looks like this:
$check=fcompcheck();
if($check)
{
$output=document.frm1.type.value+" / ";
$output=$output+"Something - "+document.frm1.disco.value+" / ";
Note the: $output variable. The dollar sign indicates a jQuery variable, right?
Thank you for any help you might be able to offer me.
Update (1-19-13): I've taken a shot at it, but I'm making slow progress. I'm used to programming Java and my JavaScript looks too similar, I can tell I'm makings errors.
I'm taking it one step at a time. Here is the logic I'm using now.
Person pastes text into text box and pushes the generate button
Program takes the contents of the text box and parses it into a large array, removing only whitespace
Program then searches for patterns in the text and begins passing values into variables
I am trying to get the program to simply identify the pattern "Summary section collapse Name" because these four words should always be in this sequence. Once it identifies this it will pass the next two array values into first and last name variables. Here's some of the code:
var contactNameFirst, contactNameLast;
// Parse the input box into an array
var inputArr = document.getElementById('inputBox').value.split(/[\s]/);
for(var i = 0; i < inputArr.length; i++)
{
if(inputArr[i] == "Summary" && inputArr[i - 1] == "section" && inputArr[i - 2] == "Collapse" && inputArr[i + 1] == "Name")
{
if(inputArr[i + 2] != "Details")
{
contactNameFirst = inputArr[i + 2];
}
else
{
contactNameFirst = "";
}
if(inputArr[i + 3] != "Details")
{
contactNameLast = inputArr[i + 3];
}
else
{
contactNameLast = "";
}
}
}
document.getElementById('contactNameOutput').innerHTML = contactNameFirst + " " + contactNameLast;
Also, should I create a new post for this now, or keep editing this one?
Your accountLinesTemp is an Array of String, you could use the Array.sort function to sort your array as expected, and then use Array.join to get the full String if necessary.
See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort on MDN for more information.