This question already has answers here:
Testing whether a value is odd or even
(23 answers)
Closed 6 years ago.
I have a function that I want to run every time my counter is 1, 3, 5 or 7. I am confused about what the right syntax is for jQuery in this situation.
My try so far:
if (i == (0, 2, 4, 6)) {
This is one of the many versions that I have tried, and failed with.
What is the right syntax, both for every odd number, as well as a specific collection of numbers, for example '3, 12, 512, 2231'?
use the modulus operator in which the value %2 will either give a 0 or a 1 depending on the value:
if (i % 2 == 1) { // code for odd event
or do it for evens:
if (i % 2 == 0) { // code for even event
What this does is divide the value by the number given (in this case 2) and returns the remainder. So if i is 5, dividing it by two will leave a remainder of 1, so its n odd number. If i = 44, dividing by two will leave a remainder of 0, so its even.
if(i % 2 == 1) //odd number
It's a modulo operator. See this documentation for more information on JavaScript arithmetic operators.
Explained in this thread.
if(i % 2) {
// If Odd then do this
}
Is this not what you're after?
i % 2 will return 1 when an odd number and 0 when an even number.
Related
This question already has answers here:
How does '&' work in relation to odd and even? In JS
(3 answers)
Closed last month.
I'm working through a problem on CodeSignal and trying to understand some of the solutions that other people have submitted. One of the solutions was as follows, and I don't understand what the ampersand is doing.
(a) => a.reduce((p,v,i) => (p[i&1]+=v,p), [0,0])
The problem is:
Several people are standing in a row and need to be divided into two teams. The first person goes into team 1, the second goes into team 2, the third goes into team 1 again, the fourth into team 2, and so on.
You are given an array of positive integers - the weights of the people. Return an array of two integers, where the first element is the total weight of team 1, and the second element is the total weight of team 2 after the division is complete.
Example
For a = [50, 60, 60, 45, 70], the output should be
solution(a) = [180, 105].
In this solution, the & operator is used to perform a bitwise AND operation. In JavaScript, the & operator compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
In the given solution, the & operator is used to determine whether the index i of the current element in the array is even or odd. If i is even, the result of i & 1 will be 0. If i is odd, the result of i & 1 will be 1.
The snippet below is what gets generated when we do a npm run dev on svelte app.
function make_dirty(component, i) {
if (component.$$.dirty[0] === -1) {
dirty_components.push(component);
schedule_update();
component.$$.dirty.fill(0);
}
component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31));
}
Can anybody please explain what is happening with the statement below? Why is the number 31 hard-coded?
component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31));
Thanks
To expand a bit on Tijmen's answer, I'll try and explain some of the rationale for this code as well as what it's actually doing.
A bitmask is a technique for storing multiple boolean options in a single integer. Say you have options A, B, C and D — you assign the values 1, 2, 4 and 8 to them, and then you can store any combination of those options like so:
AB — 3
BD — 10
ACD — 13
Later, you can retrieve the value using bitwise operators:
if (opts & 1) console.log('A was selected');
if (opts & 2) console.log('B was selected');
if (opts & 4) console.log('C was selected');
if (opts & 8) console.log('D was selected');
Svelte uses bitmasks to track which values are dirty, i.e. what has changed since the component was last updated. Because of the 31 bit limit Tijmen described, a single bitmask would only let us have 31 variables in a component — plenty in most circumstances, but certainly not all. So component.$$.dirty is an array of bitmasks.
This line of code...
component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31));
...dirties the correct bit of the correct bitmask — the (i / 31) | 0 gives us the index of the bitmask, (1 << (i % 31)) gives us the value of the bit within that bitmask, and |= sets the bit to 1, whatever its value was before.
The -1 is used as a sentinel value for indicating that the component wasn't previously dirty at all, so that Svelte can add it to the list of components that need to be updated in the next tick.
The dirty array is an array that stores multiple Boolean variables in an integer, also know as a bit array.
Integers in JavaScript are, by default, signed and 32-bit. The reason it only stores 31 bits per integer instead of 32 that because it's signed, the last bit, if set, makes the integer represent a negative number. I'm missing some context, but looking at the first if-statement, the code seems to reserve negative numbers for special cases.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I find that algorithm/functionality in two games already, but I always wanted to know what was the logic behind it.
Basically, there is a list of items and each of them has an id.
For example:
item_1 has id: 1
item_2 has id: 2
item_3 has id: 4
item_4 has id: 8
item_5 has id: 16
etc.
The id is multiplied by two every new item.
There is then a number, let's say 4, that indicate what the current item is. Is this case that would be item_3, but the tricky part is that number could also select multiple items at once like 7 which is 4 + 2 + 1 (item_3, item_2, item_1) or 17 which is 16 + 1 (item_5, item_1). It can go really high like 16384 if you have a long list and still be perfectly accurate for the multiple selections.
How do I solve this problem?
The algorithm you described is basically outputting where the 1's are in the binary representation of the number.
For 7, its binary representation is 111. There are three 1's: in the first, second, and third position from the left respectively, so it's item 1, 2 and 3. Note that we are counting from the left.
Another example:
For 10, its binary representation is 1010. There are two 1's: in the second and fourth position from the left, so the output would be items 2 and 4.
Here is an implementation in C#.
public static List<int> FindOnes(int number) {
var list = new List<int>();
var binaryString = Convert.ToString(number, 2);
for (int i = 0 ; i < binaryString.Length ; i++) {
if (binaryString[binaryString.Length - i - 1] == '1') {
list.Add(i + 1);
}
}
return list;
}
// usage:
FindOnes(7) // [1,2,3]
No idea how the games you're talking about implement it, but if this was me I would do it using bits in the binary expression of the number (example code in java).
public boolean isItemSelected(final int number, final int itemId) {
return (number & (1 << (itemId - 1))) != 0;
}
The trick here being that the binary representation of a number (from right to left) already denotes whether 1, 2, 4, 8, 16, etc. is required additively to make the number using only powers of two. The left shift simply makes a number which (in binary) is all 0's except a 1 in the 'itemId - 1'th slot. The & will match if that bit is 1 in the given number. And then checking that the result is not 0 simply turns it into a boolean.
Obviously you can combine this with some looping or anything else if you want to build the array/List of all the 'itemIds' which match.
In Javascript, you could take the number, convert it to a binary value, take the bits, reverse it and take the values (index plus one) or zero for a filtering of truthy values.
var value = 13,
items = [...value.toString(2)].reverse().map((v, i) => +v && (i + 1)).filter(Boolean);
console.log(items);
So basically i just started learning JS and had a little exercise which was basically making a function to check if the number is even without using modular arithmetic. When i was done with it i just wanted to compare mine with the answer and i couldn't really get how does it work.
function isEven(n) {
if (n == 0)
return true;
else if (n == 1)
return false;
else if (n < 0)
return isEven(-n);
else
return isEven(n - 2);
}
I'm not sure how the part (n-2) works does it somehow puts the number in a loop and basically does n-=2 until the number gets 1 or 0?
Let's take a look at what is going on behind the scenes when this function is run:
isEven(8)
// isEven(8) Is 8 even?
// isEven(6) Is 6 even?
// isEven(4) Is 4 even?
// isEven(2) Is 2 even?
// isEven(0) Is 0 even? --> Yes, the function immediately returns true
// so I know the one at the top, 8, is even
And so on. For any even number, it eventually gets to 0. For any odd number it eventually gets to 1.
If the number is negative, the function makes it positive and runs itself again against the positive value, if it's > 1, it will run itself again until the number is 1 or 0, decreasing the number by 2 on each iteration. It's called recursion.
When n <0 it puts a minus before the n in the function and runs it again. If Else then the function is called again but n is decreased by 2. This runs till you get true or false.
I had this code written by a user here yesterday and I'm having trouble understanding it. I understand all by line 9 of the deal function, it creates a random card out of 52 numbers but on the next line I don't understand what this does. Could somebody please explain what this code does so I could modify it and expand on it?
//Creates the deck
var Ace = 1;
var Face = 10;
var deck = [Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Face, Face, Face];
/*Creates a deal function that can deal cards to each player.
Use object_name.property_name = deal() to call this function.*/
var deal = function () {
var randomcard = Math.ceil(Math.random() * 52) + 1;
return deck[Math.floor(randomcard % 13)];
};
Well, first let's correct the code. The original code does give you a working result, but it does it in a confusing way. It doesn't pick a value between 0 and 51 which would be the natural thing to do, it picks a value between 2 and 53. (The result is still useful for getting a value between 0 and 12 to use for a value, but getting the suit for the card is not very straight forward.)
var randomcard = Math.floor(Math.random() * 52);
return deck[randomcard % 13];
The modulo operator gets the reminder from a division, so the result from the expression would get the value for the card. Up to 12 it returns the number itself, then at 13 it starts over at 0 again.
To get the index for the suit for the card, you would use Math.floor(randomcard / 13). With the original random value (2 to 53) you would have needed to use (Math.floor(randomcard / 13) % 4) instead.
There are 52 cards in the deck. 13 different values with 4 different suit( clubs/diamonds...). Note 4 * 13 = 52. The modulus 13 is just there to assure that one of the values from in the deck variables gets picked, and the suit is ignored.
You have an array of only 13 items -- the cards. 0 through 12.
If you take any number and % 13 it, you will always get a value between 0 and 12 -- the remainder of a division of that number by 13. The deck of 52 then % 13 basically reduces the deck from suit + card to just card.
This could have equally been written as Math.ceil(Math.random() * 13) + 1 instead of 52. However if the code needs to be expanded to also have a suit, then you might likely
The code is only half-valid. The modulo is poorly selecting the type of card to draw out of the deck, but not the suit the card is. In addition, the code doesn't account for having already dealt out a specific card (it's never removed from the deck), so multiple players could have identical cards.
See this page for information on how deck structure looks in JavaScript:
http://www.brainjar.com/js/cards/default2.asp