I have such a task. I want to create 15 divs and I want to take the background colors of these divs from the array. But here only divs are created according to 5 colors, the color of the others is undefined. How can I cycle the colors?
let color = ["yellow", "green", "red", "blue", "orange"];
for (var i = 0; i <= 15; i++) {
document.write("<div style='background:" + color[i] + "'></div> ");
}
Simple as it is, use modulo arithmetic.
Instead of color[i], use color[i % color.length], and it will work as you want.
Taking the remainder from the division of the current index by the length of the array will bind it to the range [0;length), which can allow you to repeat all array indices infinitely many times. See for yourself:
i
i % 5
0
0
1
1
2
2
3
3
4
4
5
0
6
1
7
2
8
3
9
4
10
0
11
1
12
2
13
3
14
4
15
0
try this
let color = ["yellow", "green", "red", "blue", "orange"];
for (var i = 0; i <= 15; i++) {
document.write("<div style='background:" + color[i % (color.length)] + "'></div> ");
}
Related
I'm attempting to create a game with the p5.play.js library and I've run into some problems. I want the GUI of the game to comprise x amount of squares (sprites) on board, pulled from a text file sitting in an assets folder. They have to be sprites because I want to interact with them with mouse events and other sprites. The text file is currently an 8 x 8 matrix, but I want to use any sized matrix - from 8 x8 to 24 x 24.
I've used the splitTokens function to convert each line of 8 into 8 separate strings...so far, so good! However, the conditional logic that I have used isn't interpreting the 1, 2 and 3's contained in the text file into red, green and blue. I'm not sure whether I should convert the string to an integer - I've tried that, but it didn't work...funny that!
I've only been coding for 2 months, so I'm pushing the envelope of my limited knowledge!
My code thus far:
let fileContent;
let tiles;
let spr;
function preload(){
fileContent = loadStrings('assets/game.txt');
}
function setup() {
createCanvas(500, 500);
gui = new Array(fileContent.length);
for (let i = 0; i < gui.length; i++) {
let tiles = splitTokens(fileContent[i]);
console.log(tiles);
for (let j = 0; j < gui.length; j++) {
for (let k = 0; k < gui.length; k++) {
spr = createSprite(j * 50 + 75, k * 50 + 75, 50, 50);
if (tiles[i] == "1") {
spr.shapeColor = color('red');
}
if (tiles[i] == "2") {
spr.shapeColor = color('green');
}
if (tiles[i] == "3") {
spr.shapeColor = color('blue');
}
}
}
}
}
function draw() {
background(0);
drawSprites()
}
I'm not sure where to upload any external assets here, so the current text file is as follows:
1 2 3 2 1 3 1 2
2 3 1 1 2 1 3 1
2 3 1 2 2 1 3 1
1 3 1 1 2 1 3 1
2 3 1 1 2 1 3 1
1 2 1 1 2 2 3 1
2 3 2 3 2 1 3 1
2 1 2 2 2 1 3 1
As you can see from the code, it resides in an "assets" folder.
You are triply nesting here when not necessary on a 2d matrix. Rather than iterating 64 times, you are instead iterating 512 times (with the incorrect index as well on tiles[i], changing it to the nested iterators also "works"). However I suggest you remove the j loop and rename the outer i to j. I tried to recreate based on the info you gave here, with the change in mind.
I am learning programming (with Javascript) and as a test I decided to find a way to wrote an algorithm to sort and array of strings, this is what I came up with.
// test of a sorting algorithm
var steps = 0;
var steps2 = 0;
var array = ['assa', 'erer', 'qwqw', 'ggdffdghdg', 'sdsdethhhghg', 'aaaaaa', 'gthfyjfdsfdf', 'qwqwwere', 'jygyghhf', '1', '0', '345', 'sfsdsddsfsf', 'eee3ew33', '1dwd', 'ddd2'];
var array2 = ['erer', 'jygyghhf', '1', '0', '345', 'sfsdsddsfsf', 'eee3ew33', '1dwd', 'ddd2'];
console.log('array before sort');
console.log(array);
function simpleSort(array) {
let length = array.length;
let currentPos = 1;
while (currentPos < length) {
let pivot = 0;
do {
let currentValue = array[currentPos];
if (currentValue > array[pivot]) {
array.splice(currentPos, 1);
array.splice(pivot, 0, currentValue);
steps++;
}
steps2++;
pivot++;
}
while (currentPos > pivot);
currentPos++;
}
console.log(array);
console.log('steps = ' + steps);
console.log('steps2 = ' + steps2);
}
console.log('********************');
console.log('array after sort');
simpleSort(array);
console.log('********************');
console.log('array after sort with array.sort() and array.reverse() buit in functions');
array.sort();
console.log(array.reverse());
What type of sorting algorithm would resemble most to this code and what would be the big O of this
The algorithm is the same as the following, so it has a similar structure to the O(n^2) sort algorithms.
function simpleSort(array) {
for (var currentPos = 1; currentPos < array.length; currentPos++) {
for (var pivot = 0; pivot < currentPos; pivot++) {
let currentValue = array[currentPos];
if (currentValue > array[pivot]) {
array.splice(currentPos, 1);
array.splice(pivot, 0, currentValue);
}
}
}
}
With an input of [6, 3, 5, 4, 1, 8, 6, 3], after each iteration you have:
6 3 5 4 1 8 6 3
6 3 5 4 1 8 6 3
6 5 3 4 1 8 6 3
6 5 4 3 1 8 6 3
6 5 4 3 1 8 6 3
8 6 5 4 3 1 6 3
8 6 6 5 4 3 1 3
8 6 6 5 4 3 3 1
This shows that the left side is sorted at each step, and increases in size by one each iteration. This is the same as insertion sort.
The if condition can only be true once for each iteration because after the splice, currentValue will become equal to the smallest value in the left array and compared to larger values each time. So it has O(n^2) time complexity.
I try to increase the value of a variable valuem from 0 to 10 and if the value of valuem is 10 it should decrease until the value is 0, then again increase until 10 and so on.
for example: 0 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1 0 1 2 ...
what is the simplest and efficientest way to do that?
var valuem = 0;
$('#number').text(valuem);
function count() {
valuem++;
$('#number').text(valuem);
if (valuem == 10) {
valuem--;
$('#number').text(valuem);
}
}
setInterval(count, 1000);
This way:
var valuem = 0, dir = 1;
$('#number').text(valuem);
function count() {
valuem += dir;
$('#number').text(valuem);
if (valuem < 1) dir = 1;
if (valuem > 9) dir = -1;
}
setInterval(count, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="number"></div>
You have to store the counting direction as the part of the state besides the current number to know in which direction to count when valuem is between 1 and 9.
I suppose one might simplify it more by just using the remainder with an offset. This way the entire calculation is done in a single line without any if statements.
var n = 0;
setInterval(function() {
number.innerHTML = 10 - Math.abs(n++ % 20 - 10);
}, 500);
<h1 id="number"></h1>
I have some code that loops through a collection of list elements and a collection of colours. It makes sure each list element is designated to a colour.
I understand everything about this apart from the modulus operator. I get that it finds and uses the remaining number, but I cannot for the life of me understand what it is doing here?
var li = document.getElementsByTagName('li');
var colors = ["salmon", "teal", "orange", "grey", "blue"];
var colorsCount = colors.length;
for ( var i = 0; i < li.length; i++ ) {
li[i].style.backgroundColor = colors[ i % colorsCount ]; // why does this work?
}
Since there is (potentially) a larger number of items in the li array, this prevents i from being outside the bounds of the colors array, since i % colorsCount can never be over colorsCount.
For example, if we had 10 elements in li, and 5 colors, i % colorsCount would be:
i i % colorsCount Color
-------------------------------
0 0 salmon
1 1 teal
2 2 orange
3 3 grey
4 4 blue
5 0 salmon
6 1 teal
7 2 orange
8 3 grey
9 4 blue
More Information on Modulo Operations.
i % colorsCount will set the bound of the index to be between 0 and colorsCount-1, thus ensuring you never index past the end of the array.
Since mod is the remainder, the remainder can never be greater than the divisor (which in this case, is the length of the array).
Perhaps this snippet may help you understand:
var s = ''
for (var i = 0; i < 20; i ++) {
s += (i % 5) + ', '
}
console.log(s)
The result is:
0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4,
Note how the number resets to 0 every time it reaches 5. The % colors.length just makes sure the index never goes above the array's length.
A more descriptive way of understanding:
0 % 5: 0/5 = 0, remainder 0
1 % 5: 1/5 = 1/5, remainder 1
...
5 % 5: 5/5 = 1, remainder 0
6 % 5: 6/5 = 1 1/5, remainder 1
7 % 5: 7/5 = 1 2/5, remainder 2
...
It's cycling your colours. Because you only have a limited number of colours, and any number of possible list items, it makes sure that i will not overflow the bounds of your colors array.
The modulus operator returns the remainder of division. It allows you to loop through and reuse the colors array even though there are potentially less colors in the array than there are elements in your list to color.
If length is say 8,
5 % 1 == (5 / 1) = 0 remainder 1
5 % 2 == (5 / 2) = 0 remainder 2
5 % 3 == (5 / 3) = 0 remainder 3
5 % 4 == (5 / 4) = 0 remainder 4
5 % 5 == (5 / 5) = 1 remainder 0
5 % 6 == (5 / 6) = 1 remainder 1
5 % 8 == (5 / 7) = 1 remainder 2
5 % 7 == (5 / 8) = 1 remainder 3
As you can see, the remainders are what's returned by the mod operator, and they're always less than the length of the colors array.
why does i % colorsCount work?
What it does
This code cycles through colors. It does so using the modulus operator to ensure you're always within the bounds of the array.
How it does it
Modulus operation finds the remainder of division of one number by another.
In your case by taking i modulus the colorsCount:
0 % 5; // 0
1 % 5; // 1
1 % 5; // 2
3 % 5; // 3
4 % 5; // 4
5 % 5; // 0
8 % 5; // 3
The result of a modulus operation is the remainder after division of the left operand by the right operand.
So the line of code in question will always return some number between 0 and colorsCount-1.
You iterate from 0 until how many li elements you have. For this example, say 10.
You then look at the colors array and find the element for that iteration (i) and modulus by how many items are in the colors array.
In short, this is what's happening:
var colorsCount = 10;
1 % 10 = 1 // ... Access colors[1]; (teal)
2 % 10 = 2 // .... Access colors[2]; (orange)
3 % 10 = 3 // .... Access colors[3]; (grey)
4 % 10 = 4 // .... Access colors[4]; (blue)
5 % 10 = 5 // .... Access colors[5];
etc
If you are wondering why it will never access an element outside of the array, the answer is because as i becomes greater, the result becomes smaller.
For example, take iteration 8:
8 % 5 = 3
(Iteration 8, 5 elements in the array)
Therefore you are accessing colors[3];
var tops = 5;
while (tops > 0) {
for (var spins = 0; spins < 3; spins++) {
alert("Top is spinning!");
}
tops = tops - 1;
}
Doesn't the var = spins loops 2 times each time the var = tops decreases by one until it gets to the value of 1? Wouldn't that code alert 8 times? I don't know why I get the alert 16 times.
You should get the alert 15 times, not 8 or 16.
The values of tops are 5, 4, 3, 2, 1. For each of these values, spins will be set to 0, 1 and 2.
5 (values for tops) X 3 (values for spins) = 15
You can just print to the screen the values of your variables(tops, spins).
Then you'll see that it loops 15 times and you'll see why.
Here is the jsFiddle for you:
http://jsfiddle.net/66UuT/
you spins loops for 3 times not 2 times as you are starting it from 0