Increment a numerical string: Difference between revisions
Content deleted Content added
→{{header|AppleScript}}: →AppleScriptObjC: Enhancements and fixes. Vanilla AppleScript solution in preamble. |
→sed: drastically simplified |
||
Line 3,071: | Line 3,071: | ||
<syntaxhighlight lang="scheme">(number->string (+ 1 (string->number "1234")))</syntaxhighlight> |
<syntaxhighlight lang="scheme">(number->string (+ 1 (string->number "1234")))</syntaxhighlight> |
||
=={{header| |
=={{header|sed}}== |
||
Reads a decimal integer from stdin and outputs the same with the magnitude incremented by one. |
Reads a decimal integer from stdin and outputs the same with the magnitude incremented by one. |
||
(TODO: Since it deals only with the magnitude, the result is incorrect for negative numbers—though adding this support is definitely possible.) |
(TODO: Since it deals only with the magnitude, the result is incorrect for negative numbers—though adding this support is definitely possible.) |
||
The following happens: |
|||
The routine starts by suffixing the input number with a carry mark (a <code>:</code> in this case) indicating that the digit to its left still needs to be incremented. In a loop, the following happens: |
|||
* prepend zero, if only nines (there will be an overflow) or empty |
|||
* remember the number (in hold space) |
|||
* If there is a carry mark on the far left, replace it with a 1. |
|||
* increment all digits |
|||
* If there are no more carry marks, exit the loop. |
|||
* |
* append the new number to the old one |
||
* |
* cut out everything between the two positions of the highest carry |
||
* Replace the digit with the same digit incremented by one, with 9 incrementing to a carry mark (i.e. 10). (<code>y</code>) |
|||
* If the result of such replacement was a carry mark, suffix the mark with a 0, indicating that the digit has rolled over and the digit to the left must be incremented. (<code>s</code>) |
|||
* Retrieve the held number (<code>G</code>) and replace the first carry mark and the digit to its left with the result of the computation. (<code>s</code>) |
|||
* Repeat. (<code>b</code>) |
|||
<syntaxhighlight lang="sed">s/^ |
<syntaxhighlight lang="sed">s/^9*$/0&/ |
||
h |
|||
:bubble |
|||
⚫ | |||
s/^:/1/ |
|||
x |
|||
/.:/ { |
|||
G |
|||
h |
|||
s/.9*\n.*\([^0]\)/\1/</syntaxhighlight> |
|||
⚫ | |||
s/:/:0/ |
|||
G |
|||
s/\(.*\)\n\(.*\).:\(.*\)$/\2\1\3/ |
|||
b bubble |
|||
}</syntaxhighlight> |
|||
=={{header|Seed7}}== |
=={{header|Seed7}}== |