Getting all positions of bit 1 in javascript? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have provided binary for example, 01001, and would like to get positions of bit 1, so I expect it will return me [0, 3].
Is there any function provided by javascript to get all positions of bit 1?

If it's a number, convert it to a string before hand, if it is a string you can do:
positionArray = [];
binary.split('');
for (i = 0; i < binary.length; i++){
if (binary[i] == "1"){
positionArray.push(i);
}
}
return positionArray;
What i'm essentially doing is converting the string to an array (or number to a string to an array) of characters and then going through each entry to find the positions of each '1'.
Not sure you can do it this way with numbers, which is why I suggested converting it to a string before hand. It's just a rough solution and I bet there are much better ways of doing it but hope it helps.

MDN has a useful piece of code that works numerically and will take a number like 9 or in binary 0b1001 and return you an array with true/false values depending on whether or not the corresponding bit is set in the input value. For 1001 it returns [true, false, false, true]
You can then use this array to create your desired output by checking which indexes are true, and getting [0,3]
The MDN snippet is here:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Reverse_algorithm_an_array_of_booleans_from_a_mask
And a quick example of using it is here:
https://repl.it/DuEh/5

#DibsyJr has a nice solution if you are dealing with strings. However if you start from a number, then converting it to a string is an unnecessary overhead. You can do it efficiently with this function:
function get_idxs(x) {
var arr = [];
var idx = 0;
while (x) {
if (x & 1) {
arr.push(idx);
}
idx++;
x >>= 1;
}
return arr;
}
> get_idxs(0b1001);
[0, 3]
WARNING: It does not work for negative numbers. Unfortunately for negative numbers the answer to the question depends on the underlying cpu architecture.

Related

How can i find the index of the element of an Array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Here is my code, it gives me undefined i have also tried indexof() method
let Numbers = [2,3,1,5,6,7,8 ];`
console.log("Unsorted array " + Numbers);
for(var i=0 ;i<Numbers.length;i++){`
alert(Numbers.findIndex[i]);
}
The below code would work after some changes in your code -
let Numbers = [2, 3, 1, 5, 6, 7, 8];
console.log("Unsorted array " + Numbers);
for (var i = 0; i < Numbers.length; i++) {
console.log(Numbers.indexOf(Numbers[i]));
}
In your case, you were using findIndex() which takes a function and executes it for each element of the array. You were passing it a number which is not correct. Also, the invocation of function you were doing was not correct - use () brackets and not [] brackets for function call.
Also, the i itself is the index. I don't know why you would need to use indexOf to get the index of element which you already know is present at a particular index. This method wouldn't be practical unless your array has duplicates and you need to find the first occurring index number for each element of array.
As a side tip, avoid using alert for such purposes. Stick with console log.

Javascript fill in the missing ranges (integers) [closed]

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 6 years ago.
Improve this question
I have a sorted array of objects, each with start and end coordinates, stated relative to a larger range that encompasses all of these coordinates. I would like to create new objects and put them into the array.
JsFiddle link is at the bottom.
Here's a visual representation:
before:
|---------------------------------------|
|-----| |----------| |------|
after:
|---------------------------------------|
|---|-----|-----|----------|---|------|-|
I was trying to use a for loop to find the missing ranges and then splice in the appropriate object as I found them. This creates an infinite loop.
I think that I could feasibly create a temporary array with the filled-in objects, then concatenate that with my original array and sort by start coordinate, but I'd like to do it without having to sort the array again.
Here is a link to a jsFiddle
I think your problem is, you are using splice to "modify" the subfeatures[] array, (adding a new element) but at the same time you are looping over that array, that causes infinite loop, I think your logic is good, instead of using splice, it may be easier to just construct a new array
the commented line are the only modification you have to do.(you also have to consider if the last element not ending at the upper limit)
//var newArr=[];
for (i = 0; i < subfeatures.length - 1; i++) {
//newArr.push(subfeatures[i]);
if ( subfeatures[i].end != subfeatures[i+1].start) {
var feat = {start: subfeatures[i].end, end: subfeatures[i+1].start, type: null};
console.log("A feature should be placed after the current index: "+i+". This feature would have the starting point: "+subfeatures[i].end+" and the ending point: "+subfeatures[i+1].start);
//newArr.push(feat);
}
}
//return newArr;
Splice() is not optimal because you have to move all the later elements in the array every time you find a gap. Here's the solution with a new array that Kossel is suggesting:
var newArray = [];
for (i = 0; i < subfeatures.length - 1; i++) {
newArray.push(subfeatures[i]);
if ( subfeatures[i].end != subfeatures[i+1].start) {
var feat = {start: subfeatures[i].end, end: subfeatures[i+1].start, type: null};
newArray.push(feat);
}
}

Javascript multipying without using * sign [closed]

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 7 years ago.
Improve this question
Practice Problem 1
Parameters: The function accepts two positive integers N and M.
Return Value: The function returns the product of N and M. For example, if the integers 5 and 8 are supplied to
that function, it should return the product of 5 and 8—it should return 40.
Additional
Requirements:
Do this without using the multiplication operator (*). Hint: Multiplication is just a series of addition
operations.
function mult(N, M) {
return N / (1 / M);
}
Since this is a basic excercise, I think that this answer is not expected (but maybe you'll get bonus points if you can explain it), even though it does the math without *.
function mult(N,M){
var a = new Array(N);
return a.join(""+M).split("").reduce((x,y)=>(parseInt(x)+parseInt(y)))+M
}
Note: This does not work for N < 3. No time to correct it.
OK. Look. It sounds like you're quite young so I think giving you the benefit of the doubt is alright here. So you know for the future: Stackoverflow isn't a site that you can just drop a homework question and expect people to do the work for you.
We sometimes do help with homework questions but only if it looks like you've at least attempted to answer the question yourself, by showing us some code that you've written. If you want to use SO in the future you might find the help section useful, particularly the section on how to write a good question.
OK, lecture over.
What the question is asking about is how to use a simple for loop to add some numbers together:
function getProduct(num1, num2) {
// set total to zero
// we'll be adding to this number in the loop
var total = 0;
// i is the index, l is the number of times we
// iterate over the loop, in this case 8 (num2)
for (var i = 0, l = num2; i < l; i++) {
// for each loop iteration, add 5 to the total
total += num1;
}
// finally return the total
return total;
}
getProduct(5, 8); // 40

Using a while loop to print random numbers until a certain number is reached [closed]

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 7 years ago.
Improve this question
How to use a while loop to generate random numbers until a certain number is reached? Help please
This code will generate integer numbers from 1 until 50.
var number = 50;
var x = 0;
while(x !== number){
x = Math.floor((Math.random() * 50) + 1);
console.log(x);
}
Considering there is a random number generator random you will just do as shown below
do
{
x=Math.random();
x=x*range;
if(x is desired number )
break;
else
{
print the number.
}
}while(1)
print -( desired number found).
NOTE: As you are beginner you can try the following when designing these codes..
First find what is the input and what is the output.
Then try to draw a flow chart of the whole thing ( You can try running it yourself as if you are the computer)
Then all the branch and loop are converted to if-else or for-while loop.
Check the code and match input and output.
This is a basic program structure..Instead of asking in forums about common structures try reading some books.
Hint 1: There is a function in javascript called Math.random() return a random number between 0 (inclusive) and 1 (exclusive):
Hint 2: check whether the values are equal. Use === in javascript.
Hint 3: check for if else, break and do while, while loop.
Hint 4: If you are given a random number 0<=x<1 then how do you generate a random number using in range [a,b) using the abobe geerated number? Ans: Use b*x.
hope this helps.

I want to put into variables multiple value [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to do this
if ($(this).val() in (1,2,3) ) {
...
}
I have tried this and it works but It's not what I want
if ($(this).val()==1 || $(this).val()==2 || $(this).val()==3 ) {
...
}
I notice OP is using jQuery but this should work for anyone who isn't
if([1,2,3].indexOf(yourValue) > -1) {
...
}
Edit, Gah, beaten by Blazemonger by 20 seconds
Use an array and $.inArray():
if ($.inArray(parseInt($(this).val()), [1, 2, 3]) > -1) {
}
Attempting to synthesize information that is currently scattered in a number of different answers and comments... Your code is not working because of two things:
You are using in which checks for keys, not values in an array. Thus, for example, 3 in [1,2,3] will be false, since [1,2,3] has keys (indices) 0,1,2.
Quite possibly, your value is a string
The solution is to make sure that your value is of the right type, and to use the correct function. There are two obvious choices:
indexOf - returns the index of the (first) element that matches
inArray - is available if you are using jQuery
Sample code:
var v = parseInt($(this).val()); // radix 10
var r = [1,2,3]; // the values to check against
if(r.indexOf(v) > -1) { // method 1
if($.inArray(v, r)) { // method 2
if ([1,2,3].indexOf($(this).val()) > -1) {
or
for (i in [1,2,3])
if (i==$(this).val()) {
...
}

Categories