Skip to content

Instantly share code, notes, and snippets.

@Oblongmana
Created May 8, 2013 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Oblongmana/946b14a6cedd93d90138 to your computer and use it in GitHub Desktop.
Save Oblongmana/946b14a6cedd93d90138 to your computer and use it in GitHub Desktop.
#Salesforce #apex chunk of code which will #generate a #valid #acn for you, and can then generate a valid #abn from the acn as well.
@isTest
public class abnAndAcnGenerator {
public class FailedToGenerateRandException extends Exception {}
private static final Integer RAND_ATTEMPTS_LIMIT = 5;
private static final List<Integer> ACN_WEIGHTS = new List<Integer>{8,7,6,5,4,3,2,1};
private static final List<Integer> ABN_WEIGHTS = new List<Integer>{10,1,3,5,7,9,11,13,15,17,19};
private static Set<String> acnCollisions = new Set<String>();
public static String getRandACN() {
Boolean gotMatch = false;
Integer currAttempt = 1;
while(!gotMatch && (currAttempt <= RAND_ATTEMPTS_LIMIT)) {
currAttempt++;
try {
String candidate = genACN();
if(!acnCollisions.contains(candidate)) {
acnCollisions.add(candidate);
return candidate;
}
}
catch(Exception e) {
continue;
}
}
throw new FailedToGenerateRandException('Failed to get ACN: after ' + RAND_ATTEMPTS_LIMIT + ' attempts, could not generate an ACN that has not already been generated');
return 'failed';
}
public static String genACN() {
String ACN = '';
Integer productSum = 0;
//Generate the first 8 random integers, and sum the products of the integers and their corresponding weights
for(Integer randIntIndex = 0; randIntIndex < 8; randIntIndex++) {
Integer randNum = getRandIntLessThanTen();
ACN += String.valueOf(randNum);
productSum += (randNum * ACN_WEIGHTS[randIntIndex]);
}
//Join and return the check digit with the rest of the ACN
Integer checkDigit = 10 - math.mod(productSum,10);
return ACN + (checkDigit == 10 ? '0' : String.valueOf(checkDigit));
}
public static String getABNGivenACN(String ACN) {
String ABN = '';
Integer productSum = 0;
//Extract the Integers from the ABN String, put them in the ABN string, and add to the productSum by multiplying
// the elements by their corresponding ABN Weights, beginning from index 2 (as the ABN forms the last 9 digits of the ACN)
for(Integer acnIntIndex = 0; acnIntIndex < 9; acnIntIndex++) {
Integer currInt = Integer.valueOf(ACN.mid(acnIntIndex,1));
ABN += String.valueOf(currInt);
productSum += (currInt * ABN_WEIGHTS[acnIntIndex + 2]);
}
//Join and return the check digit
Integer checkDigit = 89 - math.mod(productSum,89) + 10;
return (checkDigit < 10 ? '0' + String.valueOf(checkDigit) : String.valueOf(checkDigit)) + ABN;
}
private static Integer getRandIntLessThanTen() {
return Integer.valueOf(String.valueOf(math.random()).right(1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment