hey im trying to increase the count of this variable, num_pass, everytime we loop successffully through the if statements. it keeps spitting out 0 or 1 though.
i have tried placing the variable in many different places and declaring it in different places but still no success.
function pickup()
{
var num_pass = 0;
var i;
var array = PASSENGERS[i];
for (var i = 0; i < PASSENGERS.length; i++)
{
// get location of passengers
var lat = PASSENGERS[i].placemark.getGeometry().getLatitude();
var long = PASSENGERS[i].placemark.getGeometry().getLongitude();
// calculate distance of passengers to bus
var distance = shuttle.distance(lat, long);
// screen for freshman
// if passengers are close enough
if (distance <= 15)
{
// if there is room on the bus
// iterate through all the seats
var j;
var array = shuttle.seats;
for (j = 0;j < shuttle.seats.length;j++)
{
// if a seat is empty
if (shuttle.seats[j] == null && PASSENGERS[i].house != "Thayer Hall")
{
// remove picture from the 3-D map
var features = earth.getFeatures();
features.removeChild(PASSENGERS[i].placemark);
// remove marker from the 2-D map
PASSENGERS[i].marker.setMap(null);
// remove 2-D map attribute of passenger
PASSENGERS[i].marker = null;
// add to the shuttle
shuttle.seats[j] = PASSENGERS[i];
// update the chart
chart();
$('#announcements').html("Passenger picked up!");
$('#announcements').html("Score: " + score);
num_pass++;
}
console.log(shuttle.seats[j]);
}
}
else if (num_pass > 9)
{
$('#announcements').html("no room on bus");
}
else if (distance > 15)
{
$('#announcements').html("no passenger nearby");
}
}
This should work:
for (j = 0; j < shuttle.seats.length; j++) {
// if a seat is empty
if (shuttle.seats[j] == null && PASSENGERS[i].house != "Thayer Hall") {
// remove picture from the 3-D map
var features = earth.getFeatures();
features.removeChild(PASSENGERS[i].placemark);
// remove marker from the 2-D map
PASSENGERS[i].marker.setMap(null);
// remove 2-D map attribute of passenger
PASSENGERS[i].marker = null;
// add to the shuttle
shuttle.seats[j] = PASSENGERS[i];
// update the chart
chart();
$('#announcements').html("Passenger picked up!");
$('#announcements').html("Score: " + score);
num_pass++;
// #lukpaw explanation: Code below was unnecessary
//}
console.log(shuttle.seats[j]);
// #lukpaw explanation: Code below was unnecessary
//}
}
else if (num_pass > 9) {
$('#announcements').html("no room on bus");
} else if (distance > 15) {
$('#announcements').html("no passenger nearby");
}
}
Related
Basically, the user will input data on a new item on sheet NovoItem. When the Save Button (to be added) is pressed, the code is supposed to check on sheet2 (ArquivoItens) if the item is already there. If so, then it should break.
The code is not breaking if value is found on sheet2 (ArquivoItens):
function copyrange() {
var sourceSheet = 'Novo Item';
var destinationSheet = 'ArquivoItens';
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sourceSheet);
var ActiveUser = Session.getActiveUser();
//it add current user and a timestamp to the last 2 columns on sheet1.
var val = sheet.getRange("Q12:Q")
.getValues();
for (var i = 0; i < val.length; i++) {
if (val[i] > 0) {
sheet.getRange(12, 34, i + 1, 1)
.setValue(new Date());
sheet.getRange(12, 35, i + 1, 1)
.setValue(ActiveUser)
}
}
var LastRowSource = sheet.getLastRow();
var LastColumnSource = sheet.getLastColumn();
var values = sheet.getRange(11,1,LastRowSource,LastColumnSource).getValues();
var csh = ss.getSheetByName(destinationSheet);
var data = [];
for (var i = 1; i < values.length; i++) {
if ( values[i][0] != '') {
data.push(values[i]);
//sheet.deleteRow(i+1)
}
}
var dataNovoItem = sheet.getRange("B12:B").getValues(); // gets data (item number) in the sheet where data is input
var dataArquivoItens = csh.getRange("B2:B").getValues(); //gets the item number on the datawarehouse sheet
for(var n=1; n < dataNovoItem.length ; n++){
for(var j=1; j< dataArquivoItens.length ; j++){
if (dataNovoItem[n] != 0 && dataArquivoItens[j] != 0) {
if(dataNovoItem[n] == dataArquivoItens[j]) {
break;
}
}
}
}
Logger.log("Novo Item" + dataNovoItem);
Logger.log("ArquivoItens" + dataArquivoItens);
//Copy data array to destination sheet
csh.getRange(csh.getLastRow()+1,1,data.length,data[0].length).setValues(data);
}
Here's the log I'm getting:
Any help is appreiated.
You aren't using the iterator to access the index that you're iterating through.
It should be
for(var n=1; n < dataNovoItem.length ; n++){
for(var j=1; j< dataArquivoItens.length ; j++){
if (dataNovoItem[n] != 0 && dataArquivoItens[j] != 0) { // this is where I try to eliminate blank rows in both ranges. I've tried != '', but it gets me the same result on the print below.
if(dataNovoItem[n] == dataArquivoItens[j]) {
break; //not working
}
}
}
}
Logger.log("Novo Item" + dataNovoItem);
Logger.log("ArquivoItens" + dataArquivoItens);
I ended up solving this by iterating only through the existing list and comparing each row with the value I had set on the current sheet. This is probably too logic to yur programmers, but for a beginner like me, this can be a pain.
This is how the working is now:
var newItemID = sheet.getRange("W5").getValue(); //get the destination cell, where the item will be set
var itemIDArquivoItens = csh.getRange(2, 1, csh.getLastRow(),1).getValues(); //gets the data range where the existing ID's to be compared against are
var message = "Item já cadastrado!"; //Message to be displayed in case the ID already exists in the list;
for(j = 1; j < itemIDArquivoItens.length; j++) { //loops through existing ID
if(itemIDArquivoItens[j][0] == newItemID) { //if the ID already exists, pop up a message and stop the code from running
Browser.msgBox(message)
return;
}
}
I have the following code and need to access the variable "density" and put it in a popup. Density is defined in the mapCities function, but the markers I'm adding and the popups I'm creating are created in a for loop outside of the map cities function resulting in a ReferenceError: density is not defined
index.html:151:42. This is error is expected. I just don't know how to access that density variable. Should it be doe with a nested loop?
function mapCities(units) {
for (var i = 0; i < cities.length; i++) {
var cityName = cities[i];
var cityNumPeeps = cityPops[i];
var cityZone = cityAreas[i];
var cityXY = cityCoords[i];
var density = calcPopDensity(cityNumPeeps, cityZone, units); // call calcPopDensity passing population, cityZone and units as arguments
console.log(density);
}
};
function calcPopDensity(cityNumPeeps, cityZone, units) {
if (units == "miles") {
return cityNumPeeps / cityZone // calculate population density in miles and return it
} else if (units == "km") {
return cityNumPeeps / cityZone * 1.60934 // calculate population density in miles and return it
}
};
for (var i = 0; i < cities.length; i++) {
var cityName = cities[i];
var cityNumPeeps = cityPops[i];
var cityZone = cityAreas[i];
var cityXY = cityCoords[i];
var popup = `<b>${cityName}</b><br>
<b>population</b>: ${density}<br>`
L.marker(cityXY).addTo(map) // add marker to map based on cityCoords array and bind to popup
.bindPopup(popup);
console.log(popup)
//if statement determines units to place in popup text
if (units == "miles") {
popup += `miles`; // add text if if var density returns miles
} else if (units == "km")
popup += `kilometers`; // add text if if var density returns kilometers
L.marker(cityXY).addTo(map) // add popup again based on if statement
.bindPopup(popup);
console.log(popup)
}
```
Just create a variable for the density local to the for-loop where you need it.
The above density variable is out of scope so you won't be able to use it as is.
for (var i = 0; i < cities.length; i++) {
var cityName = cities[i];
var cityNumPeeps = cityPops[i];
var cityZone = cityAreas[i];
var cityXY = cityCoords[i];
var density = calcPopDensity(cityNumPeeps, cityZone, units);
var popup = `<b>${cityName}</b><br>
<b>population</b>: ${density}<br>`
L.marker(cityXY).addTo(map) // add marker to map based on cityCoords array and bind to popup
.bindPopup(popup);
console.log(popup)
//if statement determines units to place in popup text
if (units == "miles") {
popup += `miles`; // add text if if var density returns miles
} else if (units == "km")
popup += `kilometers`; // add text if if var density returns kilometers
L.marker(cityXY).addTo(map) // add popup again based on if statement
.bindPopup(popup);
console.log(popup)
}
I'm seeking to update the a league table by looping through a results array by player. The user populates the results through a html table beforehand.
players=[];
var players=["A","B","C"];
Results=[];
var Results=[
["Home","F","A","Away"],
["A",,,"B"],
["A",,,"C"],
["B",,,"C"],
["B",,,"A"],
["C",,,"A"],
["C",,,"B"],
];
League=[];
var League=[
["Team","P","W","D","L","F","A","Pts"],
["A",,,,,,,],
["B",,,,,,,],
["C",,,,,,,]
];
I've tried using two for loops as follows:
var pld=0;
var wins=0;
var draws=0;
var loses=0;
var goalsF=0;
var goalsA=0;
var pts=0;
for (p = 0; p <= players.length; p++)
{
for (i = 1; i < Results.length; i++)
{
if (Results[i][1]!= "")
{
if (Results[i][0]==players[p])
{
pld++;
if (Results[i][1]>Results[i][2])
{
wins++;
goalsF=+goalsF + +Results[i][1];
goalsA=+goalsA + +Results[i][2];
pts= +pts + 3;
}
else if (Results[i][1]<Results[i][2])
{
loses++;
goalsF=+goalsF + +Results[i][1];
goalsA=+goalsA + +Results[i][2];
}
else
{
draws++;
goalsF=+goalsF + +Results[i][1];
goalsA=+goalsA + +Results[i][2];
pts++
}
}
}
}
League[p][1]=pld;
League[p][2]=wins;
League[p][3]=draws;
League[p][4]=loses;
League[p][5]=goalsF;
League[p][6]=goalsA;
League[p][7]=pts;
}
Where the first two results are input, A's table values are correct but they're wrongly showing for B and C?
And when all six results are keyed on, again A's values are correct but B's and C's just accumulate?
I believe my problem is related to where I'm resetting the win, draws and losses etc counts. If I do this before the for loops (as shown above), results get counted twice, if I do this inside, nothing is counted at all.
Any guidance appreciated. Thanks!
Thanks to everyone's resposnse so far, I managed to find a solution - I reset the count variables immediately after updating the league but is there a better solution?
var pld=0;
var wins=0;
var draws=0;
var loses=0;
var goalsF=0;
var goalsA=0;
var pts=0;
for (p = 0; p <= players.length; p++)
{
for (i = 1; i < Results.length; i++)
{
if (Results[i][1]!= "")
{
if (Results[i][0]==players[p])
{
pld++;
if (Results[i][1]>Results[i][2])
{
wins++;
goalsF=+goalsF + +Results[i][1];
goalsA=+goalsA + +Results[i][2];
pts= +pts + 3;
}
else if (Results[i][1]<Results[i][2])
{
loses++;
goalsF=+goalsF + +Results[i][1];
goalsA=+goalsA + +Results[i][2];
}
else
{
draws++;
goalsF=+goalsF + +Results[i][1];
goalsA=+goalsA + +Results[i][2];
pts++
}
}
}
}
League[p][1]=pld;
League[p][2]=wins;
League[p][3]=draws;
League[p][4]=loses;
League[p][5]=goalsF;
League[p][6]=goalsA;
League[p][7]=pts;
// Reset the 'count' variables here:
var pld=0;
var wins=0;
var draws=0;
var loses=0;
var goalsF=0;
var goalsA=0;
var pts=0;**
}
This is driving me crazy! I'm very new to javascript(can read it but not always write it) My problem is threefold.User needs to input(prompt) "tall single latte".
1. I want to ad an array to this problem to store a.) the coffee strings and b.) the coffee prices.
2. I want to use a for loop to output the total amount of coffee ordered so far.
3. My output should be in table format ex.
short single latte's price is R10
double tall coffee's price is R15
var coffee = [ ];
var price = [ ];
for (var i = 0; i < 2; i++) {
var coffee = prompt("What coffee do you want:", "");
// Size
if (coffee.indexOf('short') > -1) {
var size = 7;
}
if (coffee.indexOf('tall') > -1) {
var size = 9;
}
if (coffee.indexOf('grande') > -1) {
var size = 11;
}
// Shots
if (coffee.indexOf('single') > -1) {
var shots = 1;
}
if (coffee.indexOf('double') > -1) {
var shots = 2;
}
if (coffee.indexOf('triple') > -1) {
var shots = 3;
}
// Is cappuccino?
if (coffee.indexOf('cappuccino') > -1) {
var extra = 2;
} else {
var extra = 0;
}
var price = (size + (3 * shots) + extra);
console.log(coffee + "'s price is R" + price);
}
An example of what I want to achieve:
var coffee = [ ];
var price = [ ];
coffee.push("short single latte");
price.push(10);
coffee.push("double tall latte");
price.push(15);
var i;
for (i = 0; i < coffee.length ; i++)
{
console.log(coffee[i] + "'s price is R" + price[i]);
}
I based this answer on what appears that you want to achieve (your second code-block).
-1 (often returned by functions/methods whose valid output includes 0) is called a 'sentinel value' and in javascript one catches them using ~: everything that is not -1 will coerce to true.
Further explanations as comments in code:
(window.Orders=function(){ // our constructor function
this.clr(); // init by calling clr.
}).prototype={ // set inherited methods
clr: function(){ // clear
this.coffee=[]; // empty array of unknown length
this.price=[]; // empty array of unknown length
}
, add: function(){ // build orders list
var inp, size, shots, extra;
while((inp=prompt('What coffee do you want:')) !== null){
size=0; // Size
if( ~inp.indexOf('short' ) ) size= 7;
else if( ~inp.indexOf('tall' ) ) size= 9;
else if( ~inp.indexOf('grande') ) size= 11;
shots=0; // Shots
if( ~inp.indexOf('single') ) shots= 1;
else if( ~inp.indexOf('double') ) shots= 2;
else if( ~inp.indexOf('triple') ) shots= 3;
extra= ~inp.indexOf('cappuccino') ? 2 : 0; //cappuccino?
if( size && shots ){ //abuse price to check input
this.coffee.push(inp);
this.price.push(size + 3 * shots + extra);
} else alert('please enter valid order');
}
}
, get: function(EOL){ //output orders
var i=0, L=this.coffee.length, r=new Array(L);
for(; i<L; i++){ //using a for loop as you requested.
r[i]=this.coffee[i] + "'s price is R" + this.price[i];
}
return r.join(EOL || '<br>'); //return string using arg EOL or '<br>'
}
};
<!-- HTML AND *EXAMPLE* usage -->
<button onclick="
var orders=new Orders(); // Construct new var orders
orders.add(); // Start filling it
document.getElementById('out').innerHTML=orders.get(); //get output
//orders.clr() //clears orders if you want to reuse it without spawning a new
">get orders (cancel/escape to quit)</button>
<br>
Output: <div id="out"></div>
Now.. the real challenge is thinking up way's to parse the userinput strings, determining what is valid & complete and what not (thankfully you didn't ask for solutions to that problem). I checked if size and shots are set.
Hopefully this helps your learning experience.
Thank you guys, I think I figured it out.. know its probably the long way... but...
var coffeeName = new Array();
var priceSingle = new Array();
// Loop 2 times
for ( var i = 0; i < 2; i++){
// Prompt Coffee
coffee = prompt("What coffee do you want:", "");
// Size
if (coffee.indexOf('short') > -1) {
var size = 7;
}
if (coffee.indexOf('tall') > -1) {
var size = 9;
}
if (coffee.indexOf('grande') > -1) {
var size = 11;
}
// Shots
if (coffee.indexOf('single') > -1) {
var shots = 1;
}
if (coffee.indexOf('double') > -1) {
var shots = 2;
}
if (coffee.indexOf('triple') > -1) {
var shots = 3;
}
// Is cappuccino?
if (coffee.indexOf('cappuccino') > -1) {
var extra = 2;
} else {
var extra = 0;
}
// Work out Price
var price = (size + (3 * shots) + extra);
// Push coffee to coffeeNameArray
coffeeName.push(coffee);
// Push price to priceSingleArray
priceSingle.push(price);
}
// Loop coffeeName length - Output List
for (var i = 0; i < coffeeName.length; i++)
{
console.log(coffeeName[i]+"'s price is R"+priceSingle[i]);
}
I am making a script which receives a String and separate it on smaller Strings.
Ex: "This is a long sentence, and I will separate it into smaller parts. Lalala"
It will return "This is a long sentence","and I will separate it into smaller parts","Lalala"
The aim of this is to use Google translator to transform text to speech, but this feature has a limit of about 70-80 chars, so if the string is too large I need to chop it.
First I chop in sentences separated by a dot ("."), then if there are still too long sentences, I split them with the commas (",") and if there are still too long strings I separate them in unique words.
Everything works well until I try to join some words so the audio become more continuous. For some reason the strings separated by commas get joined again. I do not know why.
This is the code:
Edit: Relevant section split out and formatted
function talk(text){
var audios = document.createElement('audio');
audios.setAttribute('id','audio_speech');
var playlist = new Array()
if(text.length >= 75) {
playlist = text.split(".");
for (var i = 0;i<playlist.length;i++) {
if (playlist[i].length >= 75) {
auxarr = playlist[i].split(",");
//alert(auxarr.length);
for(var j=0;j<auxarr.length;j++) {
auxarr2 = auxarr[j].split(" ");
document.write(auxarr2+"<br>");
if (auxarr[j].length >= 75) {
auxarr2 = auxarr[j].split(" ");
for(var x=0; x < auxarr2.length; x++){
if(auxarr2[x].length < 50) {
aux = auxarr2[x];
while (aux.length < 50 && auxarr2[x+1]) {
aux = aux + " " + auxarr2[x+1];
auxarr2.splice(x,1);
auxarr2[x]=aux;
}
}
//...
Edit: Full original code
function talk(text)
{
var audios = document.createElement('audio');
audios.setAttribute('id','audio_speech');
var playlist = new Array()
if(text.length >= 75) {
playlist = text.split(".");
for (var i = 0;i<playlist.length;i++) {
if (playlist[i].length >= 75) {
auxarr = playlist[i].split(",");
//alert(auxarr.length);
for(var j=0;j<auxarr.length;j++) {
auxarr2 = auxarr[j].split(" ");
document.write(auxarr2+"<br>");
if (auxarr[j].length >= 75) {
auxarr2 = auxarr[j].split(" ");
for(var x=0; x < auxarr2.length; x++){
if(auxarr2[x].length < 50) {
aux = auxarr2[x];
while (aux.length < 50 && auxarr2[x+1]) {
aux = aux + " " + auxarr2[x+1];
auxarr2.splice(x,1);
}
auxarr2[x]=aux;
}
}
auxarr_end = auxarr.slice(j+1,auxarr.length);
auxarr_begin = auxarr.slice(0,j);
document.write("<br>"+auxarr+"<br> aca");
document.write("<br>"+auxarr_end+"<br> aca1");
document.write("<br>"+auxarr_begin+"<br> aca2");
auxarr.splice(j,1);
auxarr_begin = auxarr_begin.concat(auxarr2);
j = auxarr.length;
auxarr = auxarr_begin.concat(auxarr_end);
alert(auxarr);
}
}
//alert("current: "+playlist[i]);
//alert("current length:"+playlist[i].length);
//alert("auxarr: "+auxarr);
playlist_end = playlist.slice(i+1,playlist.length);
playlist_begin = playlist.slice(0, i);
playlist.splice(i,1);
playlist_begin = playlist_begin.concat(auxarr);
i = playlist.length;
playlist = playlist_begin.concat(playlist_end);
//alert("new "+playlist[i]);
}
}
/*do {
textAux = text.substring(0, 74);
text = text.substring(textAux.length, text.length);
playlist.push(textAux);
}while(text.length >= 75);*/
} else {
playlist.push(text);
}
//
//playlist.push(text);
/*for(var a=0; a<playlist.length;a++){
document.write(playlist[a]+"<br>");}*/
audios.setAttribute('src', 'http://translate.google.com/translate_tts?tl=es&q=' + encodeURIComponent(playlist[0]));
playlist.splice(0,1);
audios.load();
audios.play();
/*
*/
audios.addEventListener('ended', function(){
if (playlist[0]){
audios.setAttribute('src', 'http://translate.google.com/translate_tts?tl=es&q=' + encodeURIComponent(playlist[0]));
playlist.splice(0,1);
audios.play();
}
}, false);
}
</script>
Try this, modify it to work with your constants and parameters.
var LIMIT = 20;
var res = new Array()
//strats with spliting by dot
var dotArr = "This is a long sentence. and I will separate it into smaller parts. Lalala".split(/[.]/);
for (var i = 0; i < dotArr.length; i++) {
if (dotArr[i].length > LIMIT){
//only when have to, split by comma
var comArr = dotArr[i].split(/[,]/);
for (var j = 0; j < comArr.length; j++) {
//only when have to and that a space exists, split by space
if (comArr[j].length > LIMIT && comArr[j].indexOf(" ") != -1 ){
var spaceArr = comArr[j].split(/[ ]/);
//accomulate words until we reach the limit and then push the value to res
for (var k = 0; k < spaceArr.length;){
var sMerge = spaceArr[k++];
while (k < spaceArr.length && sMerge.length + spaceArr[k].length + 1 < LIMIT){
sMerge = sMerge + " " + spaceArr[k];
k++;
}
res.push(sMerge)
}
}else{
res.push(comArr[j]);
}
}
}else{
res.push(dotArr[i]);
}
}
//res contain all optimized sentences.