I'm currently trying to realize a very simple example of genetic algorithms.
At one point, you have to do a "Cross-Over" (biology) with two numbers (parents) to get a "child".
You can find an explanation of Cross-Over here:
How to "crossover" two strings (1234 & abcd -> 12cd & ab34)
(The second illustration, the easier "one-point" Cross-Over is the one I'm trying to do.)
The chromosomes (parents and child) are numbers but the "Cross-Over" will be a bit operation.
I found a solution for one of the "chromosomes", which is the following :
Move the bits X amount to the right (>>> operator )
and then move the bits again X positions but this time to the left (<< operator)
So this would keep the end of one of the chromosomes and fill the beginning with 0s.
But I don't really know how to solve the problem of the other chromosome and then also do the Cross-Over.
(Probably a XOR once I kept the beginning / end of the chromosomes and filled the rest with 0s.)
Or should I even approach this problem from another angle?
If the fraction of the Cross-Over is p (e.g., p = .25), then this should work:
mask1 = ((0xffff >> 16*p) << 16*p)
mask2 = 0xffff ^ mask1
output1 = (input1 & mask1) ^ (input2 & mask2)
output2 = (input1 & mask2) ^ (input2 & mask1)
A couple of notes:
This is just pseudocode. You might want some casts in there.
This treats p differently than you treat it in your comment above. (Just replace p with 1-p to get to your definition of p.)
A naive approach would be to use 4 local variables:
int chromatid1Start;
int chromatid1End;
int chromatid2Start;
int chromatid2End;
Then, assign the incoming chromatid1 to the first two variables and chromatid2 to the last two variables.
chromatid1Start = chromatid1;
chromatid1End = chromatid1;
chromatid2Start = chromatid2;
chromatid2End = chromatid2;
Perform a right-shift on the Start chromatid variables up to the crossover point, then left-shift the exact same amount. On the End chromatid variables, left-shift up to the crossover point, then right-shift the exact same amount.
chromatid1Start = (chromatid1Start >> 16 * crossoverPercent) << 16 * crossoverPercent;
chromatid1End = (chromatid1End << 16 * (1 - crossoverPercent)) >> 16 * (1 - crossoverPercent);
chromatid2Start = (chromatid2Start >> 16 * crossoverPercent) << 16 * crossoverPercent;
chromatid2End = (chromatid2End << 16 * (1 - crossoverPercent)) >> 16 * (1 - crossoverPercent);
With that, you can cross the start of one with the end of the other:
int daughterChromatid1 = chromatid1Start + chromatid2End;
int daughterChromatid2 = chromatid2Start + chromatid1End;
Related
I have a weird requirement,
My destination only supports one integer, But I want to send two integers to it and later I want to get them back from a response.
for example,
allowed input:
{
'task': 2
}
I have subtask kind of a logic in my side, But my target is not aware of this. So, without letting know the target, can I somehow pack two integers and get decode them back in future?
Can this be achieved with hexadecimal?
You can combine any two numbers and get both numbers back using their product (a * b) as long as a * (a * b) + b < Number.MAX_SAFE_INTEGER
Here's a demo snippet:
(() => {
document.addEventListener("click", handleStuff);
// formula: c = (a * (a * b)) + b
// as long as c < 9007199254740991
const combine = (a, b) => ({
a: a,
b: b,
get c() { return this.a * this.b; },
get combined() { return this.a * this.c + this.b; },
get unraveled() { return [
Math.floor(this.combined / this.c),
this.combined % this.c ]; }
});
const log = txt => document.querySelector("pre").textContent = txt;
let numbers = combine(
+document.querySelector("#num1").value,
+document.querySelector("#num2").value );
function handleStuff(evt) {
if (evt.target.nodeName.toLowerCase() === "button") {
if (evt.target.id === "combine") {
numbers = combine(
+document.querySelector("#num1").value,
+document.querySelector("#num2").value );
if (numbers.combined > Number.MAX_SAFE_INTEGER) {
log (`${numbers.combined} too large, unraveled will be unreliable`);
} else {
log (`Combined ${numbers.a} and ${numbers.b} to ${numbers.combined}`);
}
} else {
log(`${numbers.combined} unraveled to ${numbers.unraveled}`);
}
}
}
})();
input[type=number] {width: 100px;}
<p>
<input type="number" id="num1"
value="12315" min="1"> first number
</p>
<p>
<input type="number" id="num2"
value="231091" min="1"> second number
</p>
<p>
<button id="combine">combine</button>
<button id="unravel">unravel</button>
</p>
<pre id="result"></pre>
Note: #RallFriedl inspired this answer
JSFiddle
Yes, you can, assuming your two integers don't contain more information than the one integer can handle.
Let's assume your tasks and sub tasks are in the range 1..255. Then you can encode
combined = (task * 256) + subtask
And decode
task = combined / 256
subtask = combined % 256
At first, you don't have to convert an integer to hexadecimal to do this. An integer is a value and decimal, hexadecimal or binary is a representation to visualize that value. So all you need is integer arithmetics to achieve your goal.
According to this answer the maximum allowed integer number in javascript would be 9007199254740991. If you write this down in binary you'll get 53 ones, which means there are 53 bits available to store within an integer. Now you can split up this into two or more smaller ranges as you need.
For example let's say you need to save three numbers, the first is always lower 4.294.967.296 (32-bit), the second always lower 65.536 (16-bit) and the third always lower 32 (5-bit). If you sum up all the bits of these three values, you'll get 53 bits which means it would perfectly match.
To pack all these values into one, all you need is to move them at the right bit position within the integer. In my example I'd like to let the 32 bit number on the lowest position, then the 16 bit number and at the highest position the 5 bit number:
var max32bitValue = 3832905829; // binary: 1110 0100 0111 0101 1000 0000 0110 0101
var max16bitValue = 47313; // binary: 1011 1000 1101 0001
var max5bitValue = 17; // binary: 1000 1
var packedValue = max32bitValue // Position is at bit 0, so no movement needed.
+ max16bitValue << 32 // Move it up next to the first number.
+ max5bitValue << 48; // Move it up next to the second number (32 + 16)
This single integer value can now be stored, cause is a perfectly valid javascript integer value, but for us it holds three values.
To get all three values out of the packed value, we have to pick the correct bits out of it. This involves two steps, first remove all unneeded bits on the lower side (by using shift right), then remove all unneeded bits on the higher side (by masking out):
var max32bitValueRead = packedValue & Math.pow(2, 32); // No bits on the lower side, just mask the higher ones;
var max16bitValueRead = (packedValue >> 32) & Math.pow(2, 16); // Remove first 32 bits and set all bits higher then 16 bits to zero;
var max5bitValueRead = (packedValue >> 48); // Remove first 48 bits (32 + 16). No higher bits there, so no mask needed.
So hope this helps to understand, how to put multiple integer values into one, if the ranges of these values don't exceed the maximum bit range. Depending on your needs you could put two values with 26 bits each into this or move the range like one 32 bit value and one 21 bit value or a 48 bit value and a 5 bit value. Just be sure what your maximum value for each one could be and set the width accordingly (maybe add one to three bits, just to be sure).
I wouldn't suggest using hexadecimal if you can not have 2 sequential numbers. Try converting to an ASCII character and then back. So if you wanted to send:
{ 'task': 21 }
You could set the 21 to a character like:
var a = 55; var b = String.fromCharCode(a); var send2 = { 'task': b };
And to convert it back it would be: var res = { 'task': b }; var original = res.task.charCodeAt();
This question already has answers here:
How to print all possible balanced parentheses for an expression?
(9 answers)
Closed 5 years ago.
Imagine I have four letters a,b,c and d. I want to determine what are the ways to validly parenthesize and multiply them. For instance (a.b).(c.d) can be a solution or (a.(b.c)).d another solution. The number of combinations is 5 for 4 letters. (Which is also equivalent to Catalan Number n-1 in that case catalan number 3 which is 5).
I have realized that these combinations can be written as full binary trees and each binary tree represents one combination :
abcd abcd
/ \ / \ .....
/ \ / \
a bcd ab cd
/ \ / \ /\
bc d a b c d
/ \
b c
Starting from the deepest leaf, algorithm can generate for instance for the first tree : 1 - (b.c) then 2 - (b.c).d then 3- a.((b.c).d).
I want to have a recursive or normal function which can generate all the possible trees and do the multiplications but not sure how I can achieve that. Any help and suggestion is greatly appreciated.
Here's a JavaScript adaptation of ninjagecko's Python code from How to print all possible balanced parentheses for an expression?
function associations(seq, kw){
var grouper = kw.grouper || ((a,b) => [a,b]),
lifter = kw.lifter || (x => [x]);
if (seq.length === 1){
return lifter(seq[0]);
} else {
var result = [];
for (let i=1; i<seq.length; i++){
// split sequence on index i
var left = seq.slice(0,i),
right = seq.slice(i);
// return cartesian product of left x right
for (let l of associations(left,kw))
for (let r of associations(right,kw))
result.push(grouper(l,r));
}
return result;
}
}
console.log(JSON.stringify(associations([1,2,3,4],{})));
I want to create a Roth IRA value calculator. The end result would accept values for annual contribution amount, interest rate, and total number of contribution years.
The calculation—a geometric series—that I need is:
Balance(Y) = P(1 + r)Y + c[ ((1 + r)Y + 1 - (1 + r)) / r ]
FWIW, I'm getting my math information here: http://www.moneychimp.com/articles/finworks/fmbasinv.htm
How would one go about writing this in Javascript? I've been reading about the math functions, but I can't seem to wrap my head around it...
I would definitely read up on JavaScripts operator precedence
A few things to note...
Grouping holds the highest precedence (), NOT with square brakets []
square brackets are for accessing object members and array literals.
There is no operator for exponents in JavaScript use Math.pow(x, n)
For mathematical operations, you MUST use operators 4(x + 1) with throw an
error telling you 4 is not a function. 4 * (x + 1) works.
The following operators are evaluated left-right * / % + - with * / %
holding equal precedence over + -. So mathematical operations are going to behave similar to pemdas.
Another note JavaScript is a dynamic loosely typed language. All numbers are 64-bit floating points, which can yield odd results in some math equations, e.g.
> .1 + .2 = 0.30000000000000004
Another good read
For solving any mathematics series below algorithm can be used. Even for some cases it will not satisfy your expected answer, but it will be correct in some other way.
Steps are as below:
1) Get the difference between the numbers as shown below:
2) Keep making difference until it seems same(difference get 0).
3) Put the same last number which is coming same in that sequence and by adding that difference complete the series by coming up.
<pre>
Examples are as below:
1 2 3 4 5 6 **7**
1 1 1 1 1 **1**
1 4 9 16 25 **36**
3 5 7 9 **11**
2 2 2 **2**
1 8 27 64 125 **216**
7 19 37 61 **91**
12 18 24 **30**
6 6 **6**
0 **0**
</pre>
The same above algorithm is implemented in below js code.
<pre>
//the input
var arr=[1,4,9,16];
var pa6inoArrayMelvo = function(arrr){
var nxtArr=[];
for(i=0;i<arrr.length;i++){
if(arrr[i+1] != undefined){
nxtArr.push(arrr[i+1] -arrr[i]);
}
}
return nxtArr;
}
var keepArray=[];
var keepAlltheArray= function(ar){
var tempArr=[];
keepArray.push(ar);
if(ar.length>1){
tempArr=pa6inoArrayMelvo(ar);
keepAlltheArray(tempArr);
}else{
generateArray(keepArray.length-1);
console.log("ans is:"+keepArray[0]);
}
}
var generateArray=function(idx){
if(keepArray[idx+1]){
var a=keepArray[idx+1];
var b=keepArray[idx];
var ans=a[a.length-1]+b[a.length-1];
keepArray[idx].push(ans);
}else{
var ans=keepArray[idx][keepArray[idx].length-1];
keepArray[idx].push(ans);
}
if(idx>0){
generateArray(idx-1);
}
}
keepAlltheArray(arr);
</pre>
As Yann Chabot said
P*(1 + r)*Y + c(((1 + r)*Y + 1 - (1 + r)) / r)
is the right answer but just as a side note, if you dont have P initialy you should set it to 1 by default.
I want to encode many things in hex. Here are examples.
var LAST_DIGITS = 0x000000A7; // Last 2 digits represent something
var MID_DIGITS = 0x00000E00; // 5th and 6th digits represent something else
Let's say I added LAST_DIGITS and MID_DIGITS together. That's 0x00000EA7 and represents the two different things I want to encode.
Is there some way I can just check a subset of that independently, in javascript/HTML5? Or do I have to turn it into a string or other collection and then reference indices explicitly?
In the above example, here's what I'm looking for
function getThemDigits (inHexValue)
{
// Check for 5th and 6th digits through my dream (not real!) function
inHexValue.fakeGetHexValueFunction(4,5); // returns 0E
// Check for last two digits for something else
inHexValue.fakeGetHexValueFunction(6,7); // returns A7
}
The common Bit-Operators (| & >> << etc.) are also available in JavaScript.
Lets assume that you always want two hexadecimal digits from the hexadecimal representation of that integer. And lets count the index of those digits from the right rather than from the left:
function GetHex(hex, offset) {
// Move the two hex-digits to the very right (1 hex = 4 bit)
var aligned = hex >> (4 * offset);
// Strip away the stuff that might still be to the left of the
// targeted bits:
var stripped = aligned & 0xFF;
// Transform the integer to a string (in hex representation)
var result = stripped.toString(16);
// Add an extra zero to ensure that the result will always be two chars long
if (result.length < 2) {
result = "0" + result;
}
// Return as uppercase, for cosmetic reasons
return result.toUpperCase();
}
Usage:
var LAST_DIGITS = 0x000000A7;
var MID_DIGITS = 0x00000E00;
var a = GetHex(LAST_DIGITS, 0);
var b = GetHex(MID_DIGITS, 2); // offset of 2 hex-digits, looking from the right
I am receiving and sending a decimal representation of two little endian numbers. I would like to:
shift one variable 8 bits left
OR them
shift a variable number of bits
create 2 8 bit numbers representing the first and second half of the 16 bit number.
javascript (according to https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators) uses big endian representation when shifting...
endianness is a bit foreign to me (I am only 90 percent sure that my outlined steps are what i want.) so swapping is a bit dizzying. please help! I only really need to know how to swap the order in an efficient manner. (I can only think of using a for loop on a toString() return value)
function swap16(val) {
return ((val & 0xFF) << 8)
| ((val >> 8) & 0xFF);
}
Explanation:
Let's say that val is, for example, 0xAABB.
Mask val to get the LSB by &ing with 0xFF: result is 0xBB.
Shift that result 8 bits to the left: result is 0xBB00.
Shift val 8 bits to the right: result is 0xAA (the LSB has "dropped off" the right-hand side).
Mask that result to get the LSB by &ing with 0xFF: result is 0xAA.
Combine the results from steps 3 and step 5 by |ing them together:
0xBB00 | 0xAA is 0xBBAA.
function swap32(val) {
return ((val & 0xFF) << 24)
| ((val & 0xFF00) << 8)
| ((val >> 8) & 0xFF00)
| ((val >> 24) & 0xFF);
}
Explanation:
Let's say that val is, for example, 0xAABBCCDD.
Mask val to get the LSB by &ing with 0xFF: result is 0xDD.
Shift that result 24 bits to the left: result is 0xDD000000.
Mask val to get the second byte by &ing with 0xFF00: result is 0xCC00.
Shift that result 8 bits to the left: result is 0xCC0000.
Shift val 8 bits to the right: result is 0xAABBCC (the LSB has "dropped off" the right-hand side).
Mask that result to get the second byte by &ing with 0xFF00: result is 0xBB00.
Shift val 24 bits to the right: result is 0xAA (everything except the MSB has "dropped off" the right-hand side).
Mask that result to get the LSB by &ing with 0xFF: result is 0xAA.
Combine the results from steps 3, 5, 7 and 9 by |ing them together:
0xDD000000 | 0xCC0000 | 0xBB00 | 0xAA is 0xDDCCBBAA.
Such function can be used to change endianness in js:
const changeEndianness = (string) => {
const result = [];
let len = string.length - 2;
while (len >= 0) {
result.push(string.substr(len, 2));
len -= 2;
}
return result.join('');
}
changeEndianness('AA00FF1234'); /// '3412FF00AA'
Use the << (bit shift) operator. Ex: 1 << 2 == 4.
I really think that the underlying implementation of JavaScript will use whatever endianess the platform it is running on is using. Since you cannot directly access memory in JavaScript you won't ever have to worry about how numbers are represented physically in memory. Bit shifting integer values always yield the same result no matter the endianess. You only see a difference when looking at individual bytes in memory using pointers.
Here is a oneliner for arrays to swap between big and little endian (and vise versa). The swapping is done using reverse on byte level. I guess for large arrays, it is more efficient than looping over scalar swap function.
function swapbyte(x) {
return new Float64Array(new Int8Array(x.buffer).reverse().buffer).reverse()
}
// Example
buf = new ArrayBuffer(16); // for 2 float64 numbers
enBig = new Float64Array(buf);
enBig[0] = 3.2073756306779606e-192;
enBig[1] = 2.7604354232023903e+199;
enLittle = swapbyte(enBig)
// two famous numbers are revealed
console.log(enLittle)
// Float64Array [ 6.283185307179586, 2.718281828459045 ]
// swapping again yields the original input
console.log(swapbyte(enLittle))
// Float64Array [ 3.2073756306779606e-192, 2.7604354232023903e+199 ]