Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coding a general 4 digit alpha-numeric series

Trying to code a general 4 digit alphanumeric series in PHP.

Pattern is as follows
0000
0001
....
....
9999
A000
A001
....
....
A999
B000
....
....
Z999
AA00
....
....
AA99
AB00
....
....
ZZ99
AAA0
....
....
AAA9
AAB0
....
....
ZZZZ

I was trying to make the logic based on the no of Z and no of 9, but could not get anything concrete going.

I am trying to write a code that will return me the next number of the series on inputting the last number of the series.

Any hints or leads will be appreciated

like image 903
Shivanshu Gupta Avatar asked Nov 08 '22 13:11

Shivanshu Gupta


1 Answers

This is actually quite easy when using PHP's built-in increment operator which is capable of handling alphanumeric sequences like this.

There are two boundary exceptions that need to be manually handled:

  1. making the first jump from numeric to alphanumeric
  2. terminating the series

<?php

function getNext($input){

  // boundary cases
  switch($input){

    // bridge numeric to alphanumeric
    case '9999': return 'A000';

    // terminate sequence, instead of expanding to 5 digits 'AAAA0'
    case 'ZZZ9': return 'ZZZA';

    // start over
    case 'ZZZZ': return '0000';

  }

  // normal increment
  $input = substr(++$input,0,4);

  // pad with leading zeros
  return str_pad($input, 4, '0', STR_PAD_LEFT);

}

$samples = [
  '0000','9999','A000','A999','Z999','AA99',
  'ZZ99','AAA9','ZZZ9','ZZZA','ZZZY','ZZZZ'
];

foreach ($samples as $sample)
  echo $sample . ' -> ' . getNext($sample) . PHP_EOL;

0000 -> 0001
9999 -> A000
A000 -> A001
A999 -> B000
Z999 -> AA00
AA99 -> AB00
ZZ99 -> AAA0
AAA9 -> AAB0
ZZZ9 -> ZZZA
ZZZA -> ZZZB
ZZZY -> ZZZZ
ZZZZ -> 0000

See this related answer.

like image 103
Jeff Puckett Avatar answered Nov 30 '22 12:11

Jeff Puckett