-1

I'm trying to convert an array of chars to an array of doubles with each one between 0-1, so that a would be 0 and z would be 1. Currently, I've thought of this method,

public static double[] charToDouble(char[] chars){
  double[] doubles=new double[chars.length];
  double one=1;
  double twentySix=26;
  double eachChar=one/twentySix;
  for(int i=0; i<chars.length; i++){
    int charNum=((int)input)-96;
    doubles[i]=eachChar*charNum;
  }
  return doubles;
}

but a would be converted to 1/26 instead of 0.

Nosrep
  • 485
  • 6
  • 16

1 Answers1

5

You need to divide by 25, not 26, because there are 25 intervals between 26 letters.

You are over-thinking your approach; you only need 1 line of code in a simple loop: simply subtract a from the char of each letter and divide the result by 25:

for(int i = 0; i < chars.length; i++) {
    doubles[i] = (chars[i] - 'a') / 25d;
}

Note the little “d” after 25 - that makes the 25 a double, which makes the result a double. If you don’t do that, you get integer arithmetic, which will make every letter except z produce 0.

Bohemian
  • 365,064
  • 84
  • 522
  • 658
  • `25 == 'z' - 'a'` (but not double) - (BTW backticks are wrong) – user85421 Jul 12 '19 at 22:38
  • @CarlosHeuberger backticks were from iPhone keyboard (fixed now), but thanks for pointing it out. The arithmetic is correct however: as long as at least one of the operands is a `double`, the calculation and result are also `double`. – Bohemian Jul 13 '19 at 01:47
  • I just mean we can (should?) use `'z'-'a'` instead of 25 (like using `'a'` instead of 96) – user85421 Jul 13 '19 at 05:55