I am creating a program which will sort people's names into different tables(table1, table2, table3, table4) which are represented by arrays and it will add any preferences that people would like to sit by into the same table as them. I have a function, check(), which makes sure there are no duplicate names and that the tables' length does not exceed 6. The problem is the check() function moves the preferences out of the table they need to be in. Is there any way to keep this from happening? Thank you.
JavaScript:
$(document).ready(function () {
var table1 = [];
var table2 = [];
var table3 = [];
var table4 = [];
var names = [];
var pref = [];
function seat() {
for (var i = 0; i < names.length; i++) {
if (pref != "") {
if (pref == names[i]) {
var who = names[i];
function prandomize(min, max) {
var pr = Math.floor(Math.random() * (max - min + 1)) + min;
if (pr == 1) {
table1.push(names[i]);
table1.push(who);
} else if (pr == 2) {
table2.push(names[i]);
table2.push(who);
} else if (pr == 3) {
table3.push(names[i]);
table3.push(who);
} else if (pr == 4) {
table4.push(names[i]);
table4.push(who);
} else {
return "Error: Contact Source Code Author!!";
}
}
}
}
function randomize(min, max) {
var r = Math.floor(Math.random() * (max - min + 1)) + min;
if (r == 1) {
table1.push(names[i]);
} else if (r == 2) {
table2.push(names[i]);
} else if (r == 3) {
table3.push(names[i]);
} else if (r == 4) {
table4.push(names[i]);
} else {
return "Error: Contact Source Code Author!!";
}
}
randomize(1, 4);
};
console.log(table1);
console.log(table2);
console.log(table3);
console.log(table4);
console.log("first call");
};
var htable1 = document.getElementById('t1');
var htable11 = document.getElementById('t11');
var htable111 = document.getElementById('t111');
var htable1111 = document.getElementById('t1111');
var htable11111 = document.getElementById('t11111');
var htable111111 = document.getElementById('t111111');
var htable2 = document.getElementById('t2');
var htable22 = document.getElementById('t22');
var htable222 = document.getElementById('t222');
var htable2222 = document.getElementById('t2222');
var htable22222 = document.getElementById('t22222');
var htable222222 = document.getElementById('t222222');
var htable3 = document.getElementById('t3');
var htable33 = document.getElementById('t33');
var htable333 = document.getElementById('t333');
var htable3333 = document.getElementById('t3333');
var htable33333 = document.getElementById('t33333');
var htable333333 = document.getElementById('t333333');
var htable4 = document.getElementById('t4');
var htable44 = document.getElementById('t44');
var htable444 = document.getElementById('t444');
var htable4444 = document.getElementById('t4444');
var htable44444 = document.getElementById('t44444');
var htable444444 = document.getElementById('t444444');
function check() {
var stable1 = table1.slice().sort();
for (var i = 0; i < table1.length - 1; i++) {
if (stable1[i + 1] == stable1[i]) {
table1.splice(i, 1);
console.log("removed");
}
}
if (table1.length > 6) {
while (table1.length > 6) {
var lastvalue = table1.pop();
table2.push(lastvalue);
console.log("moved to table2");
}
}
if (table2.length > 6) {
while (table2.length > 6) {
var lastvalue2 = table2.pop();
table3.push(lastvalue2);
console.log("moved to table3");
}
}
if (table3.length > 6) {
while (table3.length > 6) {
var lastvalue3 = table3.pop();
table4.push(lastvalue3);
console.log("moved to table4");
}
}
if (table4.length > 6) {
while (table4.length > 6) {
var lastvalue4 = table4.pop();
table1.push(lastvalue4);
console.log("moved to table1");
}
}
}
function changeHTML() {
htable1.innerHTML = table1[0];
htable11.innerHTML = table1[1];
htable111.innerHTML = table1[2];
htable1111.innerHTML = table1[3];
htable11111.innerHTML = table1[4];
htable111111.innerHTML = table1[5];
htable2.innerHTML = table2[0];
htable22.innerHTML = table2[1];
htable222.innerHTML = table2[2];
htable2222.innerHTML = table2[3];
htable22222.innerHTML = table2[4];
htable222222.innerHTML = table2[5];
htable3.innerHTML = table3[0];
htable33.innerHTML = table3[1];
htable333.innerHTML = table3[2];
htable3333.innerHTML = table3[3];
htable33333.innerHTML = table3[4];
htable333333.innerHTML = table3[5];
htable4.innerHTML = table4[0];
htable44.innerHTML = table4[1];
htable444.innerHTML = table4[2];
htable4444.innerHTML = table4[3];
htable44444.innerHTML = table4[4];
htable444444.innerHTML = table4[5];
}
function namesdefine() {
names.push(document.getElementById('nameone').value);
names.push(document.getElementById('nametwo').value);
names.push(document.getElementById('namethree').value);
names.push(document.getElementById('namefour').value);
names.push(document.getElementById('namefive').value);
names.push(document.getElementById('namesix').value);
names.push(document.getElementById('nameseven').value);
names.push(document.getElementById('nameeight').value);
names.push(document.getElementById('namenine').value);
names.push(document.getElementById('nameten').value);
names.push(document.getElementById('nameeleven').value);
names.push(document.getElementById('nametwelve').value);
names.push(document.getElementById('namethirteen').value);
names.push(document.getElementById('namefourteen').value);
names.push(document.getElementById('namefifthteen').value);
names.push(document.getElementById('namesixteen').value);
names.push(document.getElementById('nameseventeen').value);
names.push(document.getElementById('nameeighteen').value);
names.push(document.getElementById('namenineteen').value);
names.push(document.getElementById('nametwenty').value);
names.push(document.getElementById('nametwentyone').value);
names.push(document.getElementById('nametwentytwo').value);
names.push(document.getElementById('nametwentythree').value);
names.push(document.getElementById('nametwentyfour').value);
console.log(names);
var testvar = document.getElementById('nameone').value;
console.log(testvar);
console.log("Look here please");
}
function prefsdefine() {
pref.push(document.getElementById('prefone').value);
pref.push(document.getElementById('preftwo').value);
pref.push(document.getElementById('prefthree').value);
pref.push(document.getElementById('preffour').value);
pref.push(document.getElementById('preffive').value);
pref.push(document.getElementById('prefsix').value);
pref.push(document.getElementById('prefseven').value);
pref.push(document.getElementById('prefeight').value);
pref.push(document.getElementById('prefnine').value);
pref.push(document.getElementById('preften').value);
pref.push(document.getElementById('prefeleven').value);
pref.push(document.getElementById('preftwelve').value);
pref.push(document.getElementById('prefthirteen').value);
pref.push(document.getElementById('preffourteen').value);
pref.push(document.getElementById('preffifthteen').value);
pref.push(document.getElementById('prefsixteen').value);
pref.push(document.getElementById('prefseventeen').value);
pref.push(document.getElementById('prefeightteen').value);
pref.push(document.getElementById('prefnineteen').value);
pref.push(document.getElementById('preftwenty').value);
pref.push(document.getElementById('preftwentyone').value);
pref.push(document.getElementById('preftwentytwo').value);
pref.push(document.getElementById('preftwentythree').value);
pref.push(document.getElementById('preftwentyfour').value);
}
document.getElementById('sbm').addEventListener('click', function (e) {
e.preventDefault();
namesdefine();
prefsdefine();
seat();
check();
check();
check();
changeHTML();
});
console.log(table1);
console.log(table2);
console.log(table3);
console.log(table4);
console.log("second call");
console.log(pref);
});
I would suggest that you first focus on the data structures that you are using before you try to go too much further. The preferences handling is trickier than it seems at first because you could have person1 who wants to sit with person2, but person2 wants to sit beside person6. This creates a chain of preferences that is not trivial to handle.
Before you try to tackle that, I would suggest you try creating a single data structure (rather than four tables). This data structure might be an array of size 24 holding objects that looks something like this:
{ name: 'xxx', preference: 'yyy', table: n }
If you are not comfortable with objects, or arrays of objects, I would suggest that you focus your efforts on learning them since they are absolutely essential in JavaScript. Arrays are handy but, in practice, they tend to be for very simple lists or as containers to hold objects.
I could provide you code that will do what you want but I don't think that will help you in your learning curve. Take a stab at applying a different data structure and if you get stuck there, maybe post a new question on SO. There are plenty of people that want to help but you will need to do your homework to get assistance along the way.
Related
I am trying to figure out what is wrong with this following code. The code searches for value in a table and assigns mxCost. The IF..ELSE condition works for all values except 1 and is also reading the table. The IF condition makes the page crash and i am not able to figure out why? Can someone please help me figure out what i am doing wrong here. Any help will be appreciated. Thank you.
$jq("#airTableValues tbody tr").each(function() {
var monthName = months[parseInt(dateSplit[1])-1]+" "+dateSplit[0];
if(monthName==$jq(this).find("td:eq(0)").text().trim())
{
mxCost = $jq(this).find("td:eq(6)").text().trim();
}
});
if (mxCost)
mxCost = (mxCost.substring(1, mxCost.length));
else {
mxCost = 0;
}
var MxStat = document.getElementById("MxStat").value;
MxStat = MxStat/100;
var InflationRate1 = document.getElementById("InflationRate1").value;
InflationRate1 = InflationRate1/100;
var rate3 = document.getElementById("rate3").value;
rate3 = Math.pow(1+rate3/100,1/365)-1;
var mxAdj;
if (MxStat == 1){
mxAdj = mxCost;
} // <------- NOT WORKING!
else if (MxStat != 1) {
var TotalCost = mxCost * 2;
mxAdj = (TotalCost * MxStat) - mxCost;
}
var ReturnVal = (mxAdj * InflationRate1) + mxAdj;
var ReturnCalc = ReturnVal * 1000000;
var ReturnPV = Math.floor(ReturnCalc/Math.pow(1+rate3,periods));
document.getElementById("ReturnCondition").value =
(ReturnPV/1000000).toFixed(2);
ReturnCondition = ReturnVal.toFixed(2);
This worked for me
if (MxStat != 1){
var mxAdj = (TotalCost * MxStat) - mxCost;
var ReturnVal = (mxAdj * InflationRate1) + mxAdj;
aReturnCondition = ReturnVal.toFixed(2);
}
if (MxStat == 1){
var mxAdj = mxCost;
var ReturnVal = (mxAdj * InflationRate1) + mxAdj;
aReturnCondition = parseFloat(ReturnVal).toFixed(2);}
[EDIT] Full application available at: http://bit.ly/1CGZzym
I'm receiving the error:
Uncaught TypeError: Cannot set property '0' of undefined
with the following code. I believe it is due to my not declaring the child array of the 2D array properly but I am really confused as to where I should be declaring this. Any ideas would be excellent.
// Create an array for the tiles we're about to draw
var tileArray = []
is declared out side of the function.
I assume it is because I am trying to create child elements within each [col] so I guess I need to declare each col number somewhere but nothing I attempt seems to be working.
function drawGrid()
{
// Draw diamond grid
var col = 0;
var row = 0;
topTileX = (viewWidth/2);
topTileY = 0;
var nextX = 0;
var nextY = 0;
var getCols = 0;
while (topTileX > -1)
{
tileArray[col][row] = new DiamondTile(topTileX, topTileY, tileWidth, true, col, row);
tileArray[col][row].draw();
while (tileArray[col][row].xPos + tileArray[col][row].tileWidth < (viewWidth) + tileWidth)
{
col++;
nextX = tileArray[col-1][row].xPos + tileArray[col-1][row].tileWidth / 2;
nextY = tileArray[col-1][row].yPos + tileArray[col-1][row].tileHeight / 2;
tileArray[col][row] = new DiamondTile(nextX, nextY, tileWidth, true, col, row);
tileArray[col][row].draw();
if (col == getCols)
{
break;
}
}
row++;
getCols = col;
col = 0;
topTileX = topTileX - tileWidth/2;
topTileY = topTileY + tileHeight/2;
}
};
For the purpose of demonstration, the DiamondTile function is as follows:
function DiamondTile(xPos,yPos,width,interactive,myCol,myRow)
{
// Set x and y position for this sprite
this.xPos = xPos;
this.yPos = yPos;
this.myRow = myRow;
this.myCol = myCol;
// Used for AI pathfinding
this.isObstacle = false;
this.isStart = false;
this.isEnd = false;
this.gValue = 0;
this.hValue = 0;
this.fCost = 0;
this.tileWidth = width;
this.tileHeight = this.tileWidth/2;
var self = this;
// Create sprite
this.spriteObj = new PIXI.Sprite(grass);
this.spriteObj.interactive = interactive;
this.spriteObj.anchor = new PIXI.Point(0.5,0);
this.spriteObj.hitArea = new PIXI.Polygon([
new PIXI.Point(0,0),
new PIXI.Point(100,50),
new PIXI.Point(0,100),
new PIXI.Point(-100,50)
]);
this.spriteObj.mouseover = function()
{
if (self.spriteObj.tint == 0xFFFFFF)
{
self.spriteObj.tint = 0xA7E846;
}
text2.setText(self.myCol + "," + self.myRow + " Start: " + self.isStart);
}
this.spriteObj.mouseout = function()
{
if (self.spriteObj.tint == 0xA7E846)
{
self.spriteObj.tint = 0xFFFFFF;
}
}
this.spriteObj.click = function()
{
if (startStage === true)
{
startStage = false;
self.isStart = true;
self.spriteObj.tint = 0x1AFF00;
text.setText("Now select an end point");
endStage = true;
return true;
}
if (endStage === true)
{
endStage = false;
self.isEnd = true;
self.spriteObj.tint = 0xFF0000;
text.setText("Now place some obstacles");
obsStage = true;
return true;
}
if (obsStage ===true)
{
self.isObstacle = true;
self.spriteObj.tint = 0x3B3B3B;
text.setText("Press 'C' to calculate path");
return true;
}
}
};
That is a multi-dimensional array and you have not initialized the first dimension array correctly. In the while loop you have to initialize the first dimension to be able to access a second dimension element with an index:
while (topTileX > -1)
{
if (tileArray[col] == null)
tileArray[col] = [];
tileArray[col][row] = new DiamondTile(topTileX, topTileY, tileWidth, true, col, row);
tileArray[col][row].draw();
// omitted other code for brevity
}
Javascript arrays are dynamic and it's enough to initialize the first dimension array elements in this case. You don't have to initialize the individual items in the second dimension.
Update: here is a fiddle with working code http://jsfiddle.net/0qbq0fts/2/
In addition your semantics is wrong. By the book, the first dimension of a 2-dimensional array should be rows, and the second dimension should be columns.
You have to explicit create the elements representing the second dimension, e.g.:
function make2DArray(rows, cols) {
var r = Array(rows);
for (var i = 0; i < rows; ++i) {
r[i] = Array(cols);
}
return r;
}
If you don't know in advance how many columns, just use this:
function make2DArray(rows) {
var r = Array(rows);
for (var i = 0; i < rows; ++i) {
r[i] = [];
}
return r;
}
The individual rows can each have independent lengths, and will grow as you add values to them.
Similarly, if you just need to add a new (empty) row, you can just do:
tileArray.push([]);
This should probably me a comment, but SO has crashed on my side. JavaScript might be throwing an exception on your stated line, but the problem may be with the 'DiamondTile' function.
When I try var a = ar_url2.concat(ar_desc2); to join my arrays into one it returns null. I'm sure it's trivial but I spent a few hours stuck on this now and an explanation as why this is happening would be great. In my code bellow I tried while(ar_url2.length)a.push(ar_url2.shift()); and it returns same null...
function agregar() {
var i = 0,
textarea;
var ar_desc = [];
while (textarea = document.getElementsByTagName('textarea')[i++]) {
if (textarea.id.match(/^desc_([0-9]+)$/)) {
ar_desc.push(textarea.id);
}
}
var desc_count_demo = document.getElementById('desc_count').value;
var desc_count = desc_count_demo - 1;
i = 0;
var ar_desc2 = [];
var campo = null;
while (i <= desc_count) {
campo = document.getElementById(ar_desc[i]).value;
ar_desc2[ar_desc[i]] = campo;
i++;
}
i = 0;
var input;
var ar_url = [];
while (input = document.getElementsByTagName('input')[i++]) {
if (input.id.match(/^url_([0-9]+)$/)) {
ar_url.push(input.id);
}
}
var url_count_demo2 = document.getElementById('url_count').value;
var url_count2 = url_count_demo2 - 1;
i = 0;
var ar_url2 = [];
while (i <= url_count2) {
campo = document.getElementById(ar_url[i]).value;
ar_url2[ar_url[i]] = campo;
i++;
}
// var a = Array.prototype.concat.call(ar_url2, ar_desc2);
while (ar_url2.length) a.push(ar_url2.shift());
function url(data) {
var ret = [];
for (var d in data)
ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return ret.join("&");
}
window.open('alta1.php?'+url(a));
}
EDIT: If I pass to function url(ar_url2) or url(ar_desc2) the returned values in the URL are
http://localhost/proj1/alta1.php?url_0=inpit&url_1=input
and
http://localhost/proj1/alta1.php?desc_0=input&desc_1=input
But still cannot merge both into one...
One thing I see is your ar_url Array is filled by:
while(input=document.getElementsByTagName('input')[i++]){
if(input.id.match(/^url_([0-9]+)$/)){
ar_url.push(input.id);
}
}
Since you the putting the whole id in the array, it will be filled with things like: 'url_0', 'url_1', 'url_2', etc...
Later you do:
ar_url2[ar_url[i]] = campo;
When you index into ar_url, you get out the 'url_XXX' strings. That means you are setting the 'url_XXX' properties on ar_url2 instead of filling in the elements of the array.
Try changing your second loop to:
while(input=document.getElementsByTagName('input')[i++]){
var result;
if(result = input.id.match(/^url_([0-9]+)$/)){
ar_url.push(+result[1]);
}
}
To use the value captured in the ([0-9]+) portion of the RegExp instead of the entire 'url_XXX' string.
I have found similar threads about this but I cant seem to make their solutions work for my specific issue. I currently have a calendar that will highlight the starting date of an Event. I need to change this to highlight the Start Date through the End Date.
Note: I did not write this code. It seems like whoever wrote this left a lot of junk in here. Please don't judge.
attachTocalendar : function(json, m, y) {
var arr = new Array();
if (json == undefined || !json.month || !json.year) {
return;
}
m = json.month;
y = json.year;
if (json.events == null) {
return;
}
if (json.total == 0) {
return;
}
var edvs = {};
var kds = new Array();
var offset = en4.ynevent.getDateOffset(m, y);
var tds = $$('.ynevent-cal-day');
var selected = new Array(), numberOfEvent = new Array();
for (var i = 0; i < json.total; ++i) {
var evt = json.events[i];
var s1 = evt.starttime.toTimestamp();
var s0 = s1;
var s2 = evt.endtime.toTimestamp();
var ds = new Date(s1);
var de = new Date(s2);
var id = ds.getDateCellId();
index = selected.indexOf(id);
if (index < 0)
{
numberOfEvent[selected.length] = 1;
selected.push(id);
}
else
{
numberOfEvent[index] = numberOfEvent[index] + 1;
}
}
for (var i = 0; i < selected.length; i++) {
var td = $(selected[i]);
if (td != null) {
if (!(td.hasClass("otherMonth"))){
td.set('title', numberOfEvent[i] + ' ' + en4.core.language.translate(numberOfEvent[i] > 1 ? 'events' : 'event'));
td.addClass('selected');
}
}
}
},
Instead of trying to select them all, I recommend you iterate over them instead. So something like this:
function highlightDates(startDate, endDate) {
var curDate = startDate;
var element;
$('.selected').removeClass('selected'); // reset selection
while (curDate <= endDate) {
element = getElementForDate(curDate)
element.addClass('selected');
curDate.setDate(curDate.getDate() + 1); // add one day
}
}
function getElementForDate(someDate) {
return $('#day-' + someDate.getYear() + "-" + someDate.getMonth() + "-" + someDate.getDay());
}
As an extension question that Felix Kling answered so brilliantly I now need to do a two part check on the data table deployed.
Can anyone tell me how to add to the code below to allow me not only to copy the values of the pcode fields into an array but to check if there is a check in the checkbox with a corresponding row number i.e. route2 is check then add to the array but if route3 is not checked then exclude it.
function GetRoute()
{
var from = document.getElementById('inpAddr').value;
var locations = [from];
for(var i = 2; i <= 400; i++) {
var element = document.getElementById('pcode' + i);
if(element === null) { break; }
locations.push(element.innerHTML);
}
var options = new VERouteOptions();
options.DrawRoute = true;
options.RouteColor = new VEColor(63,160,222,1);
options.RouteWeight = 3;
options.RouteCallback = onGotRoute;
options.SetBestMapView = true;
options.DistanceUnit = VERouteDistanceUnit.Mile;
options.ShowDisambiguation = true;
map.GetDirections(locations,options);
}
Thanks in advance!
Justin
for( var i = 2 ; (element = document.getElementById('pcode' + i)) && i <= 400; i++ )
{
if( document.getElementById('route' + i).checked )
{
locations.push( element.innerHTML );
}
}
function GetRoute() {
var from = document.getElementById('inpAddr').value;
var locations = [from];
// My Modification Starts Here....
var maxLoopValue = 400;
var pcode, currentRoute, nextRoute;
for(var i = 2; i <= maxLoopValue; i++) {
pcode = document.getElementById('pcode' + i);
currentRoute = document.getElementById('route' + i);
// Make sure the currentRoute is 'checked'
if (currentRoute.checked) {
// Make sure there is a 'next' route before trying to check it
if (i < maxLoopValue) {
nextRoute = document.getElementById('route' + (i+1));
// Make sure the 'next' route is 'checked'
if (nextRoute.checked) {
locations.push(element.innerHTML);
}
} else {
// This is the last route, since we know it's checked, include it
locations.push(element.innerHTML);
}
}
}
// My Modification Ends Here....
var options = new VERouteOptions();
options.DrawRoute = true;
options.RouteColor = new VEColor(63,160,222,1);
options.RouteWeight = 3;
options.RouteCallback = onGotRoute;
options.SetBestMapView = true;
options.DistanceUnit = VERouteDistanceUnit.Mile;
options.ShowDisambiguation = true;
map.GetDirections(locations,options);
}