开发者

Incrementing array values - Arduino

开发者 https://www.devze.com 2023-03-04 16:53 出处:网络
I\'m trying to increment some array values: int counter[] = {0,0,0,0,0,0,0,0}; If the value of the number in position 0 reaches 25, then the value in position 1 is incremented by 1, and position 0

I'm trying to increment some array values:

int counter[] = {0,0,0,0,0,0,0,0};

If the value of the number in position 0 reaches 25, then the value in position 1 is incremented by 1, and position 0 reset to 0. And so on - when index position 2 reaches 25 it increments position 3 by 1, and resets it's own value to 0.

I'm doing some base26 incrementing - generating all the combinations of letters for a given number of letters. Ideally I'd like开发者_开发知识库 this to work infinitely (in theory) - a new array index is appended when the last value reaches 25.

I'm working on the project which this previous question relates to - might clear up what I'm trying to do: Every permutation of the alphabet up to 29 characters?

Here's the code I have at the minute:

// Set the variables.
String neologism;
int counter[] = {0,0,0,0,0,0,0,0};
String base26[] = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};

void setup() {
    // Initialize serial communication:
    Serial.begin(9600);
}

void loop() {
    int i = 0;
    // Reset or increment the counter.
    if (counter[i] == 25) {
        counter[i] = 0;
        counter[i+1]++;
    }
    else {
        counter[i]++;
    }
    neologism = letters(counter[i]);
    Serial.print(neologism+'\n');
    delay(100);
    i++;
    if(i>7) {
        i=0;
    }
}

String letters(int counter) {
    String newword;
    for(int i=0; i <= 7; i++) {
        newword += base26[counter];
    }
    return newword;
}


Use class java.math.BigInteger.


There is not much point using a data type longer than a long as it will take centuries to reach Long.MAX_VALUE.

You can just increment a long and convert this to base 26 as required.

A simple way to convert a positive long to base26 is to do

 public static String base26(long n) {
     if (n == 0) return "0";
     StringBuilder sb = new StringBuilder();
     while(n > 0) {
         sb.insert(0, (char) ('a' + n % 26));
         n /= 26;
     }
     return sb.toString();
 }
0

精彩评论

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

关注公众号