增加数组值 - Arduino

时间:2011-05-08 20:06:19

标签: java math arduino

我正在尝试增加一些数组值:

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

如果位置0中的数字值达到25,则位置1的值增加1,位置0重置为0.依此类推 - 当索引位置2达到25时,它将位置3递增1,并将其自身值重置为0.

我正在做一些base26递增 - 为给定数量的字母生成所有字母组合。理想情况下,我希望无限制地工作(理论上) - 当最后一个值达到25时,会附加一个新的数组索引。

我正在处理上一个问题涉及的项目 - 可能会清除我正在尝试做的事情: Every permutation of the alphabet up to 29 characters?

这是我现在的代码:

// 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;
}

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:2)

使用超过long的数据类型没有太大意义,因为需要几个世纪才能达到Long.MAX_VALUE。

您只需增加一个长整数,然后根据需要将其转换为26。

将正长度转换为base26的简单方法是执行

 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();
 }