finding an index by recursively cutting the array in half - javascript

I want to find an index making the less possible yes/no questions in a x^2 array, for this I assumed a cool approach will be to find the col position by cutting at the half (or near the half) and asking is col <= half? depending on the answer, I will pick one of the halves and repeat this until the length == 1, then make the same but with is row <= half? to find the row.
This is my function (first time attempting a recursive function):
function recursiveFunc(indexPos, currentArrLen, moveIndexBy, countLoops){
var aproxHalf, relativeIndexPos;
relativeIndexPos = (indexPos-moveIndexBy);
aproxHalf = Math.floor(currentArrLen/2);
if(currentArrLen<2){
return (moveIndexBy+" "+countLoops);
}else{
countLoops++;
if(relativeIndexPos>=aproxHalf){
moveIndexBy += aproxHalf;
currentArrLen -= aproxHalf;
}else{
currentArrLen = (aproxHalf-moveIndexBy);
}
return recursiveFunc(indexPos, currentArrLen, moveIndexBy, countLoops);
}
}
The only var that seems non self explanatory might be relativeIndexPos, so I will explain it, the value of it is the index of the index we are trying to find but within only the smaller array (e.g if we had 5x5 finding index 2, the new array length after cutting it once is 3, the relative index of 2 in that array [0,1][<2>,3,4] is 0)
edit: okay maybe I should explain moveIndexBy, it basically is "the leftest index at the current working array"
It works on a 5x5 array, for example if I give x the values of 0 to 4 in recursiveFunc(x,5,0,0);, it will correctly find the index in the less possible questions <index/questions> 0:2, 1:2, 2:2, 3:3, 4:3.
But this fails with bigger arrays, for example, a 10x10 will give:
0 3
1 3
2 3
3 4
4 4
5 2
5 2
7 3
8 4
9 4
The 5 and others are wrong, it can't possibly find 5 in 2 steps: 0 1 2 3 4 (5 6 7 8 9) then 5 6 (7 8 9) you still need to see if the index is the left or right of 5 (6). Also it fails to even find the index 6

currentArrLen = (aproxHalf-moveIndexBy);
to
currentArrLen = aproxHalf;
I don't know what or why, but that fixed it:
0 3
1 3
2 3
3 4
4 4
5 3
6 3
7 3
8 4
9 4
edit: with that, an undocumented bug of length being sometimes 0 is fixed too, so change if(currentArrLen<2) to if(currentArrLen==1)

Related

Fastest way to read large collection of objects

I need to store a large collection of small objects (chord diagrams) that will not change. It is a javascript project.
I have two questions:
how should I store these objects? As json, as text,... ?
what's the fastest way to find a specific item?
I search the item by it's key + type + "/" + bass:
Example: I get Am7/C# and I need to find the corresponding diagram. The key would be the file.
For now it's using only one file and search it with regex:
"{define: C frets x 3 2 0 1 0 fingers 0 3 2 0 1 0}",
"{define: C(add9) frets x 3 2 0 3 0 fingers 0 2 1 0 3 0}",
I will have 90 000 chords that I can split in 12 files (one for each key).
My object can look like this:
{type="m" bass="" frets="x 3 1 0 1 3" fingers="0 3 1 0 2 4" variation="1"}
I read a bit about binary search but I don't know if this can help me.
Thanks!

Algorithm to obtain the item(s) at a precise number [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 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);

jQuery if sentence on variable odd number [duplicate]

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.

how to check number in range with n level

Today i have a hard work, and hard issue:
lets say i have js function which each time we call it, it return a number :
let's say i have list number from 1 to 100 in array, and make it into columns and rows:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17
18 19 20 21 ...
each time call function, it return random number in 1 > 100, but i need to check:
if number is 1, 2, 3 or 7, 8, 9 ( because array number will sort to 6 columns each row, so i need to detect number return from function is one of 3 digis left, or 3 digis right ).
and because number range not fixed, i dont know what math or solution to detect this case.
anyone know it?
To get a column number (or, more precisely, "left 3 or right 3") subtract 1 and do a % modulus operator: (value-1) % 6. The result will be 0..2 (or "left column") or 3..5 (so "right column").

Titanium SQLite: Database pseudo array

I have a working app that needs to store up to 4 matrixes of integer data per record. I'm not sure how to get there with Titanium and SQlite.
A record will contain at least 1 but up to 4 matrixes of integers:
The matrix size is variable, each matrix consists of:
1 - 20 rows with 3 columns per row
OR
1 - 20 rows with 6 columns per row
The matrix structure will be identical for each record, i.e. 3 3x20 matrixes in
a record or 4 6x10 matrixes in a record. At this point my app starts, allows the user to choose the matrix parameters then accepts the data entry to fill in the matrix values. The matrixes are actually an JS array of arrays. How can I store an array of arrays and read it back in when I need to?
Edit: Let me see if I can clarify...
The app I'm working on is a scorecard for archery tournaments, similar in concept to a scorecard in golf. In archery you shoot for a set number of ends with a set number of arrows shot per end. The app asks for the number of ends (up to 20) and the number of arrows shot per end (3 or 6). After each shot the archer enters the score (an integer value). so for argument's sake say we're scoring for three ends with three arrows per end. We might see something like this:
arrow scores
8 8 9 (end 1)
7 9 10 (end 2)
9 9 10 (end 3)
There's my matrix that I need to save for this individual record. However, the next tournament I need to score may have a different number of ends and arrows:
arrow scores
7 8 9 10 10 10 (end 1)
10 9 9 7 8 10 (end 2)
9 6 6 6 9 9 (end 3)
7 8 6 7 8 8 (end 4)
10 10 9 8 8 8 (end 5)
Let's simplify and say that I want to store the scorecard for one archer per record. I already have my data entry and score tabulation working. I just don't understand the best way to store matrices as illustrated above.
I would recommend against storing an array of arrays. Generally speaking, its not terribly efficient to write abstractions with code that are meaningful for reasoning about matrices when make array of arrays a firm concept. The only exception I've seen is matlab/octave.
I've always found I end up with simpler code when I flatten the data. With a flat array you'll have to manage the indexing yourself. A few helper functions make that simple to reason about.
I'm not given much info to go on, but I'd assume that putting the data into two different tables will make things simpler.
CREATE TABLE mat3x20 (i1j1, i1j2, i1j2 ....
CREATE TABLE mat6x10 (i1j1, i1j2, i1j2 ....
Otherwise you have some weird behavior flag in the data which will make it less obvious what the code is supposed to be doing somewhere in the call stack.

Categories