-1

I'm trying to code a PHP function to generate a 3-letter code. The first letter must be X,Y or Z and it must follow these format: XAA, XAB, XAC .... until XAW then XBA, XBB, XBC .... Until XBW then XCA, XCB..... etc.

When 'X' is done, then YAA, YAB, so on... When 'Y' is done ZAA, ZAB, so on...

The 2nd and 3rd letter of this code cannot be X,Y or Z.

I am fetching last generated code from the database.

Here is what I have so far.. Confused about final conditions:

$valid = str_split("ABCDEFGHIJKLMNOPQRSTUVW");

if($result->num_rows() < 1)
    $last_code = 'XAA';
else {
    $result = $result->row_array();
    $last_code = $result['employee_code'];
}

$arr = str_split($last_code);

$first  = $arr[0];
$second = $arr[1];
$third  = $arr[2];

if($first == 'X') {

} else if($second == 'Y') {

} else if($third == 'Z') {

}
ITFreak
  • 83
  • 2
  • 10

2 Answers2

0

The logic is quite simple, because PHP has the following mechanic:

$letter = 'a';
echo ++$letter; // echoes 'b'

This is doumented good in this question

Now all you need to make sure yourself are the boundries of your code:

  1. If the second and/or third letter are 'W', it gets replaced with an 'A' and the previous letter get incremented.
  2. If the first letter is 'Z' and shall be incremented, the algorithm can not generate a new code.

In all other cases it is sufficient to simply increment the last letter.

if($result->num_rows() < 1) {
    //If no code exists the new code is XAA, not the old one.
    return 'XAA';
}

$result = $result->row_array();
$last_code = $result['employee_code'];
$new_code = $old_code;

if ($old_code[2] === 'W') {
    if ($old_code[1] === 'W') {
        if ($old_code[0] === 'Z') {
            throw new Exception('All codes used! Add new algorithm');
        } 
        $new_code[0] = ++$old_code[0];
        $new_code[1] = 'A';
    } else {
        $new_code[1] = ++$old_code[1];
    }
    $new_code[2] = 'A';
} else {
    $new_code[2] = ++$old_code[2];
}
return $new_code;

The first two if conditions handle boundry 1, while the third if condition handles boundry 2. The else blocks handle the increment of the letter.

Philipp Maurer
  • 2,480
  • 6
  • 18
  • 25
0

I have coded a simpler logic:

public function generate_code() {
    $result = $this->db->query("SELECT employee_code FROM employees ORDER BY id DESC LIMIT 1");

    $invalid = str_split("XYZ");

    if($result->num_rows() < 1)
        $last_code = 'XAA';
    else {
        $result = $result->row_array();
        $last_code = $result['employee_code'];
    }

    $last_code++;

    while(in_array($last_code[1], $invalid)) {
        $last_code++;
    }

    while(in_array($last_code[2], $invalid)) {
        $last_code++;
    }

    return $last_code;
}
ITFreak
  • 83
  • 2
  • 10