0

I realize that arrays were not built this way in PHP. however I am experimenting with genetic algorithms for the first time, and as PHP is the language most familiar to me, I am writting it in PHP, later I will change it to Python. Anyway, i have two input arrays, one of which being:

$geneValues = array(
    '0000' => 0,
    '0001' => 1,
    '0010' => 2,
    '0011' => 3,
    '0100' => 4,
    '0101' => 5,
    '0110' => 6,
    '0111' => 7,
    '1000' => 8,
    '1001' => 9,
    '1010' => '+',
    '1011' => '-',
    '1100' => '*',
    '1101' => '/');

each key is a "gene" that stores a value. I am attempting to do this completely hands off other than the initial array setting, i have a function that creates The initial population by randomly combining the above array genes into a multidimensional array which groups the genes into, you guessed it, chromosomes. so i could have a chromosome that looks like: 011010100111 meaning => 6 + 7 this all works great. However I am at the point where I need to actually "compute" the chromosome, however as the addition operator has to be in quotes in the array, it makes a literal + and not the operator. My question is, is there any way that I can get the operators in my array to be actual operators, I know of know function that will do this, and the only other option i can come up with would be to hard code the gene to the operator when i do the computations, which is what im trying to avoid.

I will post the whole code if needed, it's nothing sensitive, just trying to ease my way into neural networks and figured i would start with implementing genetic algorithms. Any one have a solution?

Halter
  • 48
  • 2
  • 6
  • 30

3 Answers3

3
$geneValues = array(
    '0000' => 0,
    '0001' => 1,
    '0010' => 2,
    '0011' => 3,
    '0100' => 4,
    '0101' => 5,
    '0110' => 6,
    '0111' => 7,
    '1000' => 8,
    '1001' => 9,
    '1010' => '+',
    '1011' => '-',
    '1100' => '*',
    '1101' => '/');

$chromosome = '011010100111';
list($operand1, $operator, $operand2) = str_split($chromosome, 4);

switch($geneValues[$operator]) {
    case '+' : $result = $geneValues[$operand1] + $geneValues[$operand2]; break;
    case '-' : $result = $geneValues[$operand1] - $geneValues[$operand2]; break;
    case '*' : $result = $geneValues[$operand1] * $geneValues[$operand2]; break;
    case '/' : $result = $geneValues[$operand1] / $geneValues[$operand2]; break;
}
echo $result;
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • + for use of `str_split()`. Are we sure the middle element will be the *operator*? – Jason McCreary Jul 30 '13 at 21:14
  • +1 the middle element must be the operator else the chromosom should get small fitness – bitWorking Jul 30 '13 at 21:15
  • If chromosome has the structure that OP has indicated, and can guarantee that there will always be an operator as the middle gene in the chromosome: there's also a potential divide by zero possibility as well – Mark Baker Jul 30 '13 at 21:16
  • Yes the middle element has to be an operator else the chromosome will not work, and thanks for point out the divide by zero issue, I'll have to take that into consideration also, can't believe i didn't think of using `switch`! genious. though i will probably have to go the eval route to avoid the hard code, and eval only seems to be evil if user input is in the mix – Halter Jul 30 '13 at 21:17
  • -1, this is specifically the kind of solution the OP asked NOT to provide – user428517 Jul 30 '13 at 21:17
  • if the chromosom size is dynamic it should check alternating if chromosom is an operator and only then perform the operation. – bitWorking Jul 30 '13 at 21:20
  • @redreggae - but then you get into operator precedence, and need a full arithmetic parser, such as that provided as an answer by ircmaxell to this [question](http://stackoverflow.com/questions/12692727/how-to-make-a-calculator-in-php)... or don't genes follow arithmetic rules? – Mark Baker Jul 30 '13 at 21:22
  • @redreggae yeah the computing function will have to take this into consideration, i had originally planed to factor this into the beginning, but i feel like my hands would be too into it if i determined the original chromosome structure, after all we dont get to decide how our genes are made :) – Halter Jul 30 '13 at 21:23
  • i don't get why people think i'm trolling. **read the question**: `My question is, is there any way that I can get the operators in my array to be actual operators, I know of know function that will do this, and the only other option i can come up with would be to hard code the gene to the operator when i do the computations, which is what im trying to avoid.` as such, @tobiaskun's answer is the only one that is acceptable. the ones that don't answer the question at all get -1. not trolling. – user428517 Jul 30 '13 at 21:23
  • 1
    Id assumed (perhaps erroneously) that `hard code the gene to the operator` meant actually having a PHP `function` as the array value: perhaps @nope could clarify – Mark Baker Jul 30 '13 at 21:24
  • @MarkBaker yeah..good point. I think I have to rethink my own genetic codes ;) – bitWorking Jul 30 '13 at 21:25
  • @MarkBaker i should have been a tad more clear on that, i was refering to avoiding `if($gene == '+')` then add.. etc. rather something like the reverse of pythons `str()` function, but that works on operators, eval seems to be the simplest. – Halter Jul 30 '13 at 21:30
1

You think like I do.

In PHP, no you can't treat operators as data (without eval). If you try again in LISP you have a different story.
As all your operator are > 0x09, it is easy to detect them. If you wrote them as function pointers; rather than a piece of text, you could detect via is_callable() then execute them, passing the other items as data. This isn't hardcoding in that whatever you put in the function can be run. If you have no concern about performance, you can dynamically create the functions via create_function().
As a last option, you could use eval() e.g. eval() a text buffer containing all three genes. What you are doing doesn't have user input, so the normal security advisories don't apply.

If this was Perl, one would probably make the numbers function results in addition.

Have you thought about writing your initial genes out in decimal, or hex? It would be easier to read. When doing this you would need to use bit masks to pull the correct nibble out.

Owen Beresford
  • 712
  • 4
  • 10
0

Have a look at eval. But be careful with it.

Example:

$value1 = 6;
$value2 = 3;
$operand = "-";
//$result will be 3
$result = eval("return (" . $value1 . $operand . $value2 . ");");
Tobias Golbs
  • 4,586
  • 3
  • 28
  • 49
  • why the downvote? this will certainly work (although @tobiaskun your link is to the german site) – user428517 Jul 30 '13 at 21:11
  • @sgroves: I've asked that myself too. Thx for the tip with the german link though. – Tobias Golbs Jul 30 '13 at 21:13
  • Going with this one because it's the simplest syntax (imo) and it will fit in smoothly. – Halter Jul 30 '13 at 21:25
  • 2
    and what you're doing with all the parse errors like `eval('return (+7-);')` ? – bitWorking Jul 30 '13 at 21:31
  • @redreggae I'm going to have to have checks and balances, those chromosomes will certainly get a lower fitness rating and not "survive" – Halter Jul 30 '13 at 21:33
  • @redreggae: Really? The questioner asked about a function that could execute code live. So i told him about one. He should be aware that there surely could be parse errors while combining the array data. And the way he asked his question shows to me that he not will try to shuffle all data wildly together. – Tobias Golbs Jul 30 '13 at 21:35
  • 1
    I didn't downvote..just wanted to make clear that it can be dangerous, since chromosomes ARE widly shuffled. So there has to be some checks before using `eval` or error handling etc. – bitWorking Jul 30 '13 at 21:38
  • + For answering the question the OP *seemed* to be asking. For the record, I don't hate `eval()`. It has it's places. This may be one. I just don't use it. And most don't. Hence the random down votes. – Jason McCreary Jul 30 '13 at 21:38
  • @redreggae: I removed this phrase from my comment immediately after the posting. Because i do no know if you downvoted and if so it is your right to do so. I'm sorry for that. I should have added a stronger warning though! – Tobias Golbs Jul 30 '13 at 21:40
  • @JasonMcCreary: I do not like using eval myself. In fact i did not used it one single time in my "coding" life! But like you and redreggae stated, i should have added an big and fat warning sign "Do not use" :D – Tobias Golbs Jul 30 '13 at 21:43
  • I think eval is totally ok in this case and an easy way to do correct arithmetic operations with dynamically sized chromosomes like Mark Baker stated. You just have to check if numbers and operators always alternate. – bitWorking Jul 30 '13 at 21:47
  • How i like that. All the downvoters that do not read the question at all! Great community work! – Tobias Golbs Jul 31 '13 at 06:35