开发者

function for writing out a base 7 word, like binary counter style

I need a function similar to the ones explained here...

JS function for writing out a word, binary counter style

...but using base 7 (or others) to generate (count) letters up from A to G Like so...

---a  
---b  
---c  
---d  
---e  
---f  
---g  
--aa  
--ab  
--ac  
--ad  
--ae  
--af    

etc. up to gggg  

Is there a simple way to change one 开发者_C百科of those functions to make this happen?

p.s. This is pretty cool...

They used...

var iterations = Math.pow(2,str.length)   
and Math.pow(string.length,2)  

They both work but only because the string length was 4 and the base was 2

inadvertently correct

i.e 4^2=16 2^4=16   

If any other string length was used one of them becomes wrong.

i.e. 2^10=1024 10^2=100   


Maybe this is gives a first start: Working Demo

It basically just takes a number and converts it to a base 7 number:

var map = 'abcdefg';

var n = 13
var out = '';
if(n == 0) out = map.charAt(0) + out;
while (n > 0) {
    out = map.charAt(n % 7) + out;
    n = Math.floor(n / 7);    
}   
// gives "bg" for 13

This would imply maintaining a normal counter in decimal system and convert every number.

Note that aa in this system does not exit, as a maps to 0.


function change_num(num,base) {
    var lets = 'abcdefghijklmnopqrstuvwxyz';
    lets = lets.split('');
    if (num / base < 1) {
        return lets[num];
    }
    if (num / (Math.pow(base,2)) < 1) {
        return lets[Math.floor(num/base)] + lets[(num % base)];
    }
    if (num / (Math.pow(base,3)) < 1) {
        var numreturn;
        numreturn = lets[Math.floor(num/(Math.pow(base,2)))];
        numreturn += lets[Math.floor((num%Math.pow(base,2))/base)];
        numreturn += lets[(num % base)];
        return  numreturn;
    }
    if (num / (Math.pow(base,4)) < 1) {
        var numreturn;
        numreturn =  lets[Math.floor(num/Math.pow(base,3))];
        numreturn += lets[Math.floor(num%Math.pow(base,3)/(Math.pow(base,2)))];
        numreturn += lets[Math.floor((num%Math.pow(base,2))/base)];
        numreturn += lets[(num % base)];
        return numreturn;
    }
    if (num / (Math.pow(base,5)) < 1) {
        var numreturn;
        numreturn = lets[Math.floor(num/Math.pow(base,4))];
        numreturn += lets[Math.floor(num%Math.pow(base,4)/(Math.pow(base,3)))];
        numreturn += lets[Math.floor(num%Math.pow(base,3)/(Math.pow(base,2)))];
        numreturn += lets[Math.floor((num%Math.pow(base,2))/base)];
        numreturn += lets[(num % base)];
        return numreturn;
    }

}

Works for any base. Couldn't be bothered to write a recursive function so did it the hard way, you can probably infer what I'm doing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜