Author: Jonas Bilinkevicius
How do I pull out every second digit from a string and sum them?
Answer:
This is a rather unusual question, but it's not that hard to accomplish.
What must iterate through each character of the string and "grab" the digits whose
position is a multiple of two (2). There are a couple of ways to do this, but I
took what I felt was the easier route. Since this is more or less a binary problem,
setting a Boolean value with each iteration works nicely. Here's the logic:
For all "odd" positions, set Boolean value to False;
For all "even" positions, set Boolean value to True;
If the Boolean value is true, grab that character and add it to a temporary buffer.
Iterate through the buffer, and convert each character to an Integer while adding
the converted value to an integer variable.
Here's the code that accomplishes the above:
1 2 function AddEvenOrOddChars(S: string; OddOrEven: Boolean): Integer;
3 var4 I: Integer;
5 evn: Boolean;
6 buf: string;
7 begin8 Result := 0;
9 10 {If OddOrEven was passed as True, then the all odd positions11 will be grabbed and summed. If False, then all even positions12 will be grabbed and summed.}13 evn := EvenOdd;
14 15 {First grab the even position characters}16 for I := 1 to Length(S) do17 begin18 if evn then19 buf := buf + S[I];
20 21 {Set boolean to its opposite regardless of its current value.22 If it's currently true, then we've just grabbed a character.23 Setting it to False will make the program skip the next one.}24 evn := not evn;
25 end;
26 27 {Now, iterate through the buffer variable to add up the individual28 values}29 for I := 1 to Length(buf) do30 Result := Result + StrToInt(buf[I]);
31 end;