Use jquery to distribute array elements to list randomly - javascript

I have a simulator here that's working just fine, this simulator have 48 blocks (DIV elements), i'm using Math.floor((Math.random() * 48) + 1) to randomly attach the results on each block. The problem is that they're too close on the final simulation (see image below):
Is there a jquery / javascript function where i can return the array items from the simulation odd/even? Like, it will add each block like: 1,3,5,7,9 then 2,4,6,8.
My code looks like this right now:
if(adicionados.length < 48)
{
while(i<=eE && adicionados.length < 48)
{
sol = Math.floor((Math.random() * 48) + 1);
if(adicionados.length == 0 || adicionados.indexOf(sol) == -1)
{
adicionados.push(sol);
//console.log(adicionados);
$("#base"+sol).attr("src", foto);
$("#base"+sol).attr("data-i", $(this).parent().parent().find('.relacionados-img').attr('data-cor'));
i++;
}
}
Thanks!

You can use just two for loop because you have fixed row and col number and you are trying to draw a fixed pattern.
for(var i=1;i<=8;i++)
{
for(var j=1;j<=6;j++)
{
var sol=(i*6)+j;//if you are naming the boxes from left to right.
if(i%2==1)
{
if(j%2==1)
{
//your code to draw those boxes.
}
}
else
{
if(j%==0)
{
//your code to draw those boxes.
}
}
}
}

Related

Iterating through different-sized grids to play audio for Conway's Game of Life

So I have an iteration question for my version of Conway's Game of Life (That is not my code, just an example of the game logic). So basically there are multiple sizes of the game board, going from 32(W)X16(H), and increasing in powers of 2 to 1024(W)X512(H). I am creating an audio version, so that whenever a cell becomes alive, web audio plays an oscillator note for a brief duration. The frequency and gain of that note depends on where on the board the audio is located. I have 32 frequency nodes and 16 gain nodes, so the cell at the top most right of the board would play the note at the highest frequency and the largest gain (.8). My problem comes when the board sizes increases, such as 64X32. I am having trouble figuring out the logic of how to determine which note and gain to use, as the cells in position 0 and 1 (left to right from the bottom) would have the same frequency, as would the cells in position 0 and 1 (bottom to top from the left corner) be having the same gain. Here is the code for my portion where I am having problems:
function updateGame()
{
// GO THROUGH THE UPDATE GRID AND USE IT TO CHANGE THE RENDER GRID
for (var i = 0; i < gridHeight; i++)
{
for (var j = 0; j < gridWidth; j++)
{
// HOW MANY NEIGHBORS DOES THIS CELL HAVE?
var numLivingNeighbors = calcLivingNeighbors(i, j);
// CALCULATE THE ARRAY INDEX OF THIS CELL
// AND GET ITS CURRENT STATE
var index = (i * gridWidth) + j;
var testCell = updateGrid[index];
// CASES
// 1) IT'S ALIVE
if (testCell === LIVE_CELL)
{
if (gridWidth == 32)
{
if (gainHeight == 0)
{
gainNode[0].gain.value = .05;
osc[i].connect(gainNode[0]);
gainNode[0].connect(context.destination);
}
else {
gainNode[j].gain.value = .05 * j;
osc[i].connect(gainNode[j]);
gainNode[j].connect(context.destination);
}
osc[i].start(context.currrentTime);
if (context.currentTime == .5)
{
gainNode[0].gain.value = 0;
osc[i].connect(gainNode[0]);
gainNode[0].connect(context.destination);
}
}
else if (gridWidth == 64) //issues begin here
{
if (gainHeight == 0 && (j == 0 || j == 1))
{
}
else
{
}
}
else if (gridWidth == 128)
{
}
else if (gridWidth == 256)
{
}
else if (gridWidth == 512)
{
}
else {
}
// 1a FEWER THAN 2 LIVING NEIGHBORS
if (numLivingNeighbors < 2)
{
// IT DIES FROM UNDER-POPULATION
renderGrid[index] = DEAD_CELL;
}
// 1b MORE THAN 3 LIVING NEIGHBORS
else if (numLivingNeighbors > 3)
{
// IT DIES FROM OVERCROWDING
renderGrid[index] = DEAD_CELL;
}
// 1c 2 OR 3 LIVING NEIGHBORS, WE DO NOTHING
else
{
renderGrid[index] = LIVE_CELL;
}
}
// 2) IT'S DEAD
else if (numLivingNeighbors === 3)
{
renderGrid[index] = LIVE_CELL;
}
else
{
renderGrid[index] = DEAD_CELL;
}
}
}
}
I haven't actually implemented the audio portion of the code yet, as I wanted to make sure I had the correct logic going forward before I started messing with web audio. I have an array filled with 32 oscillator nodes, and an array filled with 16 gain nodes valued from .05 to .8. Thanks for the help, and hopefully this made sense!
It should be as simple as dividing the coordinate by how much you are scaled up past 32x16. For a width of 64, you'd use Math.floor(i/2) instead of just i. Sorry if this was obvious and I missed the point of the question...

Display images according to number set from interval

i try to display from svg ,layers according to numbers set from an interval.I have 2 random numbers (left and right) set to display from interval (10,99) both.That works good,but, i need to display layer 1(banane1) from svg if left || right belongs to interval (10,20) , then if left || right belongs to interval (20,30) to display layer 2(banane2) from svg and so on untill left || right belongs to interval (90,99) to display layer 9(banane9). There are 9 intervals and 9 layers from svg to display. Code i wrote looks like :
FIDDLE: http://jsfiddle.net/r68Bg/
for(var i = 0; i < 2; i++){
panouri = document.getElementById('panou' + i);
svgDoc = panouri.contentDocument;
}
where panou0 and panou1 are 2 svg that has layers 2 numbers where i display later random numbers set from intervals and 9 layers each with different content which must be displayed according to random numbers.
function randomIntFromInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
};
function conditions(){
left = randomIntFromInterval(10,99);
right = randomIntFromInterval(10,99);
for(var i = 0; i < 2; i++){
ecuations.push(left, right);
randoms = document.getElementById("panou" + i).contentDocument;
numere = randoms.getElementById("number");
numere.textContent = ecuations[i];
}
};
where i add into my svg (panou0 and panou1) randoms numbers from set intervals.
function setBananeState(state)
{
for(var i = 1; i < 10; i++){
svgItem = svgDoc.getElementById("banane" + i);
svgItem.setAttribute("display", "none");
svgItem = svgDoc.getElementById(state);
svgItem.setAttribute("display", "inline");
}
};
function getBanane(){
if(left || right >= 30 && left || right <= 40){
bananeState = "banane3";
setBananeState(bananeState);
}
};
Here i have all layers from svgs which contains bananas to display according to random number given and a function getBanane() which has condition to display layer1 (banane1 by id from svg) if random number is from interval (10,20).Unfortunately this doesnt work...and i must have 8 more condition to display layers from svg if random numbers are from different interval
This isn't going to work:
if(left || right == randomIntFromInterval(10,20)){
What you are doing here is a ORing left with right which will give you a boolean which you are then comparing to randomIntFromInterval. I think what you are trying to do is this:
var interval = randomIntFromInterval(10,20);
if (left == interval || right == interval) {
EDIT: Okay you changed your question. So now this:
if(left || right >= 30 && left || right <= 40){
Is not right, you can't write an if statement like that in javascript, or in most (probably all) programming languages. You can't say "if a or b is greater than x", like you would in normal English speech because it's ambiguous. You have to explicitly say "if (a is greater than x) or (b is greater than x)". So your if statement above needs to become:
if ((left >= 30 || right >=30) && (left <= 40 || right <= 40)) {
Although I'm not sure this is exactly what you want either. Because here if left==0 and right==41, then this statement would be true. I think you want either left or right to be in the interval, so your best check would be:
if ((left >= 30 && left <= 40) || (right >= 30 && right <= 40)) {

What is wrong with this code? Am I going about this the right way?

Okay, so I'm fairly new to programming. I've been learning to code for quite sometime now, but I hadn't really MADE anything. That considered, I'm attempting to make my first project using JavaScript and make a snake game. Unfortunately, I've ran into multiple problems, which obviously is something that comes hand in hand with programming, but I am new and I'm stuck. Can someone help me figure out if I'm coding this in an efficient way. Also, I have a more specific issue. I've added basic movement functionality to the head of my snake, but I can't figure out how to get the rest of it's parts to follow. If someone could explain to me how to do this, that would be incredible. I've worked about two weeks now to try and figure it out and I'm just stumped. I'm using Raphael's JavaScript Library to generate the graphics on an SVG canvas.
/*
Libraries in use:
1. Rapheal
2. jQuery
*/
// This variable is set to an array so that we can add multiple snakeParts to our PrimarySnake.
var snakeParts = [],
// This variable uses Raphael to generate a canvas.
snakeCanvas = Raphael(10, 10, 400, 400),
// This generates a rectangle that fills the canvas.
snakeCanvasBg = snakeCanvas.rect(0,0,400,400),
// This variable is set to an array so that we can use each and every direction that is pressed.
direction = [],
// This variable is set to an array so that we can use the turn coordinates of our first snake part.
turnCoords = [];
// Generates and returns a random number between 0 and 400. This function is used to help generate the goal of our snake at a random location on the canvas.
function getRandNum () {
var rand = Math.round(Math.random()*400);
// This while loop ensures that our snakeGoal never exceeds the coordinates x = 390 or y = 390. If it did, it's parts would be cut from the canvas.
while (rand > 395) {
rand = Math.round(Math.random()*400);
}
// This while loop ensures that our rand variabe will always be divisible by 10, which is used to make sure our snakeGoal and snakePart elements are always rendered in coordinates divisible by 10.
while (rand % 10 !== 0) {
var randString = rand.toString(),
// This variable stores the whole length of our randString variable.
randStringLength = randString.length,
// This variable stores the last number of our rand as a string character.
subtractionChar = randString.charAt(randStringLength - 1),
// This variable stores the last number of our rand as a integer.
subtractionInt = parseInt(subtractionChar),
// Finally, this line subtracts the last number of our rand from the entirety and then sets that value equal to rand, ensuring that rand is always divisible by 10.
rand = rand - subtractionInt;
}
return rand;
}
// This function is called any time a button is pressed. The jQuery which method allows our code to compare if the key pressed is equal to the keyCode of a designated key.
$(document).keydown(
function (pressedDirection) {
if (pressedDirection.which === 37) {
direction.push("left");
} else if (pressedDirection.which === 38) {
direction.push("up");
} else if (pressedDirection.which === 39) {
direction.push("right");
} else if (pressedDirection.which === 40) {
direction.push("down");
} else if (pressedDirection.which === 32) {
direction.push("stop");
}
if (pressedDirection.which === 37 || pressedDirection.which === 38 || pressedDirection.which === 39 || pressedDirection.which === 40 || pressedDirection.which === 32) {
console.log(direction[direction.length - 1]);
PrimarySnake.addTurnCoords();
PrimarySnake.movePeice();
}
// This prevents our screen from scrolling when an arrow key is
pressedDirection.preventDefault();
}
);
function Snake () {
// This method generates a new peice to the Snake.
this.addPart = function () {
console.log(snakeParts.length);
snakeParts[snakeParts.length] = snakeCanvas.rect(0,0,10,10);
snakeParts[snakeParts.length - 1].attr("fill", "blue");
snakeParts[snakeParts.length - 1].attr("stroke-width", ".25");
}
// This method provides the movement functionality of our Snake.
this.moveDirection = function () {
for (value in snakeParts) {
var currentCoord = [snakeParts[value].attr("x"), snakeParts[value].attr("y")];
// This if-else statement moves the snakePart at the -value- index up, down, left, or right according to the last direction pressed.
if (direction[direction.length - 1] === "up") {
snakeParts[value].attr("y", currentCoord[1] - 10);
} else if (direction[direction.length - 1] === "down") {
snakeParts[value].attr("y", currentCoord[1] + 10);
} else if (direction[direction.length - 1] === "left") {
snakeParts[value].attr("x", currentCoord[0] - 10);
} else if (direction[direction.length - 1] === "right") {
snakeParts[value].attr("x", currentCoord[0] + 10);
}
}
}
this.moveInterval;
// This function makes our moveDirection move our snakePeice every 50 milliseconds.
this.movePeice = function () {
var moveDirection = this.moveDirection;
// clearInterval is used to eliminate any interval previously running, ensuring that our peices only move one direction at a time.
clearInterval(this.moveInterval);
this.moveInterval = setInterval(function(){moveDirection()}, 50);
}
// This function adds an array of coordinates to the turnCoords array.
this.addTurnCoords = function () {
turnCoords.push([snakeParts[0].attr("x"), snakeParts[0].attr("y")]);
}
}
// This generates a new instance of our Snake class.
var PrimarySnake = new Snake();
// This generates a new part on the canvas.
PrimarySnake.addPart();
// This fills our snakeCanvasBg with a grey color, giving us a grey background.
snakeCanvasBg.attr("fill", "#CDCDCD");
Well, your code seems nice, or at least "efficient" as you are calling it.
To make the parts of your snake follow its head, you must iterate through its parts and assign each (n+1) piece the coordinates from (n). To do so, start with the last piece and iterate up to the first one, which movement is defined by the user, like in:
this.moveDirection = function () {
// Move every piece except the head.
for (var i = snakeParts.length - 1; i > 0; i--) {
snakeParts[i].attr("x", snakeParts[i-1].attr("x"));
snakeParts[i].attr("y", snakeParts[i-1].attr("y"));
}
// Now move the head.
if (direction[direction.length - 1] === "up") {
snakeParts[value].attr("y", currentCoord[1] - 10);
} else if (direction[direction.length - 1] === "down") {
snakeParts[value].attr("y", currentCoord[1] + 10);
} else if (direction[direction.length - 1] === "left") {
snakeParts[value].attr("x", currentCoord[0] - 10);
} else if (direction[direction.length - 1] === "right") {
snakeParts[value].attr("x", currentCoord[0] + 10);
}
}
That code may need a bit of work but that's the idea. Hope it helps!

Keep an index within bounds and wrap around

I am doing a little carousel with a pager. The carousel displays elements 6 by 6 and I have 36 elements to display. I have a next and previous button. The first elements displayed are [0, 6]. If I press the previous button and there is no previous elements (eg I am on the first page), it should wrap around and go to the end. The same applies for the last elements and the next button.
My code looks like this:
$('#img_prev').click(function (e) {
# change this line so it wraps around
imgIndex = (imgIndex - 6) % 36;
alert(imgIndex)
refreshImages(imgIndex);
e.preventDefault();
return false;
});
$('#img_next').click(function (e) {
imgIndex = (imgIndex + 6) % 36;
refreshImages(imgIndex);
e.preventDefault();
return false;
});
And it fails miserably because -6 % 36 is -6 and not 30. I could handle it with if (index < 0) ... but I would prefer a condition with a modulo that best capture the wrapping behavior.
How can I get this to wrap around (see 2nd line) ?
One possible solution would be with this answer:
function mod(x, m) {
return (x%m + m)%m;
}
$('#img_prev').click(function (e) {
# this line has been changed, now it wraps around
imgIndex = mod(imgIndex - 6, 36);
...
You could try this:
var maxElements = 36;
$('#img_prev').click(function (e) {
// change this line so it wraps around
imgIndex = (maxElements - 1) - (imgIndex % maxElements);
alert(imgIndex)
refreshImages(imgIndex);
e.preventDefault();
return false;
});
$('#img_next').click(function (e) {
imgIndex = (imgIndex % maxElements);
refreshImages(imgIndex);
e.preventDefault();
return false;
});
Here's a fiddle showing the output of:
(imgIndex % maxElements)
and
(maxElements - 1) - (imgIndex % maxElements);

Use jquery to dynamically number table columns diagonally

Hi there fellow coders,
I'm looking to find a way to fill a pre-built dynamic blank table with numbering (and colouring if possible) like so:
As you can see the numbering is ascending order diagonally. I know there's probably some way to calculate the number based on the tables td index but can't quite figure out how to do that for every column diagonally. Any help would be appreciated.
Update: Ok back from my Holidays. Thanks to all you clever people for your replies. As I'm sure you've all had to experience the pain in the neck clients can be, I've been told the spec has changed(again). This being the case I've had to put the grid/matrix into a database and output using a pivot table. Every square has to be customizable color-wise.
Nothing is going to waste though I have learnt quite a few nifty new javascript/jquery tricks from your responses I didn't know about before, so thanks, and I'll be sure to pay it forward :)
Here's what I came up with in the end.
Given you said "colouring if possible" I'll provide an example solution that doesn't do colours quite the way you want (it does it in a way that I found easier to code and more attractive to look at) but which does handle all the numbering correctly for varying table sizes.
The function below assumes the table already exists; in this demo I've included code that generates a table to whatever size you specify and then calls the function below to do the numbering and colours.
function numberDiagonally(tableId) {
var rows = document.getElementById(tableId).rows,
numRows = rows.length,
numCols = rows[0].cells.length,
sq = numRows + numCols - 1,
d, x, y,
i = 1,
dc,
c = -1,
colors = ["green","yellow","orange","red"];
diagonalLoop:
for (d = 0; d < sq; d++) {
dc = "diagonal" + d;
for (y = d, x = 0; y >= 0; y--, x++) {
if (x === numCols)
continue diagonalLoop;
if (y < numRows)
$(rows[y].cells[x]).html(i++).addClass(dc);
}
}
for (d = 0; d < sq; d++)
$(".diagonal" + d).css("background-color", colors[c=(c+1)%colors.length]);
}
Demo: http://jsfiddle.net/7NZt3/2
The general idea I came up with was to imagine a square twice as big as whichever of the x and y dimensions is bigger and then use a loop to create diagonals from the left edge of that bounding square going up and to the right - i.e., in the order you want the numbers. EDIT: Why twice as big as longer side? Because that's the first thing that came into my head when I started coding it and it worked (note that the variable i that holds the numbers that get displayed is not incremented for the imaginary cells). Now that I've had time to think, I realise that my sq variable can be set precisely to one less than the number of rows plus the columns - a number that ends up rather smaller for non-square tables. Code above and fiddle updated accordingly.
Note that the background colours could be set directly in the first loop, but instead I opted to assign classes and set the loops for each class later. Seemed like a good idea at the time because it meant individual diagonals could be easily selected in jQuery with a single class selector.
Explaining exactly how the rest works is left as an exercise for the reader...
UPDATE - this version does the colouring more like you asked for: http://jsfiddle.net/7NZt3/1/ (in my opinion not as pretty, but each to his own).
This fiddle populates an existing table with numbers and colors. It is not limited to being a 5x5 table. I didn't understand the logic of 15 being orange rather than yellow, so I simply grouped the diagonal cells into color regions.
// we're assuming the table exists
var $table = $('table'),
// cache the rows for quicker access
$rows = $table.find('tr'),
// determine number of rows
_rows = $rows.length,
// determine number of cells per row
_cols = $rows.first().children().length,
// determine total number of cells
max = _rows * _cols,
// current diagonal offset (for coloring)
d = 1,
// current row
r = 0,
// current cell
c = 0;
for (var i=1; i <= max; i++) {
// identify and fill the cell we're targeting
$rows.eq(r).children().eq(c)
.addClass('d' + d)
.text(i);
if (i < max/2) {
// in the first half we make a "line-break" by
// moving one row down and resetting to first cell
if (!r) {
r = c + 1;
c = 0;
d++;
continue;
}
} else {
// in the second half our "line-break" changes to
// moving to the last row and one cell to the right
if (c + 1 == _cols) {
c = 1 + r;
r = _rows -1;
d++;
continue;
}
}
r--;
c++;
}
Here's a jsFiddle that does what you asked for - http://jsfiddle.net/jaspermogg/MzNr8/8/
I took the liberty of making it a little bit user-customisable; it's interesting to see how long it takes the browser to render a 1000x1000 table using this method :-D
Assuming that each cell has an id of [column]x[row], here are teh codez for how to fill in the numbers of a square table of side length sidelength.
//populate the cells with numbers according to the spec
function nums(){
var xpos = 0
var ypos = 0
var cellval = 1
for(i=0;i<2*sidelength;i++){
if(i >= sidelength){
ypos = sidelength - 1
xpos = 1 + i - sidelength
$('td#' + xpos + 'x' + ypos).text(cellval)
cellval = cellval + 1
while(xpos + 1 < sidelength){
ypos = ypos-1
xpos = xpos+1
$('td#' + xpos + 'x' + ypos).text(cellval)
cellval = cellval + 1
}
} else {
ypos = i
xpos = 0
$('td#' + xpos + 'x' + ypos).text(cellval)
cellval = cellval + 1
while(!(ypos-1 < 0)){
ypos = ypos-1
xpos = xpos+1
$('td#' + xpos + 'x' + ypos).text(cellval)
cellval = cellval + 1
}
}
}
}
And here they are for how to colour the bugger.
// color the cells according to the spec
function cols(){
if(+$('td#0x0').text() === 99){
return false
} else {
$('td').each(function(index, element){
if(+$(this).text() > 22)
{
$(this).attr("bgcolor", "red")
}
if(+$(this).text() <= 22)
{
$(this).attr("bgcolor", "orange")
}
if(+$(this).text() <= 14)
{
$(this).attr("bgcolor", "yellow")
}
if(+$(this).text() <= 6)
{
$(this).attr("bgcolor", "green")
}
})
}
}
Enjoy, eh? :-)

Categories