2017/06/27

Random String

公司有一個需求想要產生 unique id,雖然 PHP 有 uniqid 可以使用,但他最基本的長度是 13 個字元,所以決定自己刻一個利用 0-9、a-z 產生的亂數密碼,會有 PHP、nodejs 以及 shell script 版本。

PHP
<?php

function code($length = 10)
{
    $codeString = '0123456789abcdefghijklmnopqrstubwxyz';
    $codeStringSplit = str_split($codeString);
    $codeStringSize = count($codeStringSplit);
    $code = '';

    for ($i = 0; $i < $length; ++$i) {
        $rand = mt_rand(0, $codeStringSize - 1);
        $code .= $codeStringSplit[$rand];
    }

    return $code;
}

for ($i = 0; $i < 10; $i++) {
    echo code().PHP_EOL;
}
node.js
function code(length) {
    var stringLength = length || 10;
    var codeString = '0123456789abcdefghijklmnopqrstubwxyz';
    var codeStringSplit = codeString.split('');
    var codeStringSize = codeStringSplit.length;
    var code = '';
    var min = 0;
    var max = codeStringSize - 1;

    for (var i = 0; i < stringLength; ++i) {
        var rand = Math.floor(Math.random() * (max - min + 1)) + min;

        code += codeStringSplit[rand];
    }

    return code;
}

for (var i = 0; i < 10; ++i) {
    console.log(code());
}
bash
#!/bin/bash

function code() {
    result=""
    length=10
    codeString="0123456789abcdefghijklmnopqrstubwxyz";
    declare -a array

    for (( i = 0; i < ${#codeString}; i++ )); do
        array+=(${codeString:$i:1})
    done

    if [[ -n $1 ]]; then
        declare -i length=$1
    fi

    max=$((${#array[@]} - 1))
    
    for (( i = 0; i < ${length}; i++ )); do
        rand=$(shuf -i 0-${max} -n 1)
        result="${result}${array[${rand}]}"
    done

    echo ${result}
}

for (( j = 0; j < 10; j++ )); do
    code
done

沒有留言: