Jump to content

Increment a numerical string: Difference between revisions

→‎{{header|AppleScript}}: →‎AppleScriptObjC: Enhancements and fixes. Vanilla AppleScript solution in preamble.
(→‎{{header|AppleScript}}: →‎AppleScriptObjC: Enhancements and fixes. Vanilla AppleScript solution in preamble.)
Line 515:
----
===AppleScriptObjC===
The task description's delightfully unspecificunforthcoming about what's meantit means by "increment" ("add 1" as in C-related languages or "add a certain amount" as in English?) and what's meant by "numerical string" covers with regardrespect to formatsize, number type, format, locale, and base. ThisAt attemptsits tomost covertrivial, mostgiven basesa string exceptrepresenting fora basemodest, itselfunformatted decimal integer, whichthe isvanilla strictlyAppleScript decimalsolution here.would be:
 
<syntaxhighlight lang="applescript">{("1234612345", "+ 1,000,000,000,000,004",) "8.77",as text --> "8,77E+012346"}</syntaxhighlight>
The task description's delightfully unspecific about what's meant by "increment" ("add 1" as in C-related languages or "add a certain amount" as in English?) and what's meant by "numerical string" with regard to format, number type, locale, and base. This attempts to cover most bases — except for base itself, which is strictly decimal here.
 
The following handles more possibilities, but the number base is still resolutely decimal:
 
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
 
-- Using the machine's own locale setting. The numerical text must be compatible with this.
-- Params: Numerical text or NSString, AppleScript or Objective-C number or text equivalent.
on incrementNumericalString:str byAmount:incrementSizeincrement
set localeID to current application's class "NSLocale"'s currentLocale()'s localeIdentifier()
return my incrementNumericalString:str byAmount:incrementSizeincrement localeID:localeID
end incrementNumericalString:byAmount:
 
-- Including athe locale ID as aan additional parameter.
-- Params: As above plus locale ID (text or NSString).
on incrementNumericalString:str byAmount:incrementSizeincrement localeID:localeID
set |⌘| to current application
set str to |⌘|'s class "NSString"'s stringWithString:(str)
set locale to |⌘|'s class "NSLocale"'s localeWithLocaleIdentifier:(localeID)
set decSeparator to locale's objectForKey:(|⌘|'s NSLocaleDecimalSeparator)
-- We'll use an NSNumberFormatter to generate NSDecimalNumber objects for the math
set regex to options:(|⌘|'s NSRegularExpressionSearch) range:({0, output's |length|()})
-- as its string conversion methods are more flexible than NSDecimalNumber's own.
-- We'll useUse an NSNumberFormatter to generate the NSDecimalNumber objects for the math,
-- as its number/string conversion methodsconversions are more flexible than NSDecimalNumber's own.
tell |⌘|'s class "NSNumberFormatter"'s new()
its setGeneratesDecimalNumbers:(true)
its setLocale:(locale)
set eRangesymbolRange to str's rangeOfString:("[Ee]| ?[x*] ?10 ?\\^ ?") options:(|⌘|'s NSRegularExpressionSearchregex)
if (eRangesymbolRange's |length|() > 0) then
-- "E"Catered-for orexponent "e"symbol in the input string. Set the output style to "scientific".
its setNumberStyle:(|⌘|'s NSNumberFormatterScientificStyle)
set esymbol to str's substringWithRange:(eRangesymbolRange)
its setExponentSymbol:(esymbol) -- Same case as the original.
else
-- Straight base 10 numerical text, with or without separators as per the input and locale.
its setNumberStyle:(|⌘|'s NSNumberFormatterDecimalStyle)
set groupingSeparator to locale's objectForKey:(|⌘|'s NSLocaleGroupingSeparator)
its setUsesGroupingSeparator:(str's containsString:(groupingSeparator))
its setMinimumFractionDigits:(str's containsString:(decSeparator))
end if
-- GenerateDerive andNSDecimalNumbers addfrom the NSDecimalNumbersinputs, add andtogether, convert the result back to NSString.
set decNumincrement to its(|⌘|'s numberFromStringclass "NSArray"'s arrayWithArray:(str{increment}))'s firstObject()
setif ((increment's to its numberFromStringisKindOfClass:(incrementSize|⌘|'s class "NSNumber")) as textboolean) then ¬
set outputincrement to its stringFromNumber:(decNum's decimalNumberByAdding:(increment))
set sum to (its numberFromString:(str))'s decimalNumberByAdding:(its numberFromString:(increment))
set output to its stringFromNumber:(sum)
end tell
-- Adjustments for AppleScript norms the NSNumberFormatter may omit from scientific notation output:
-- If the input style's scientific and has a "+" after the "E" or "e" , insert a "+" at that point
if (symbolRange's |length|() > 0) then
-- in the output if there's no sign there already. NSNumberFormatter only includes minus signs.
-- If no decimal separator in the output mantissa, insert point zero or not to match the input style.
if ((eRange's |length|() > 0) and ((str's containsString:((e as text) & "+")) as boolean)) then ¬
set output toif ((output's stringByReplacingOccurrencesOfStringcontainsString:("(?<=[Ee]decSeparator)(?=\\d)") withString:("+"as boolean) ¬then
if ((eRange's |length|() > 0)else andif ((str's containsString:((e as text) & "+"decSeparator)) as boolean)) then ¬
options:(|⌘|'s NSRegularExpressionSearch) range:({0, output's |length|()})
set output to output's stringByReplacingOccurrencesOfString:("(?<=^-?\\d)") ¬
withString:((decSeparator as text) & "0") options:(regex) range:({0, output's |length|()})
end if
-- If no sign in an E-notation exponent, insert "+" or not ditto.
if (((output's rangeOfString:("[Ee][+-]") options:(regex))'s |length|() > 0) as boolean) then
else if (((str's rangeOfString:("[Ee][+-]") options:(regex))'s |length|() > 0) as boolean) then
set output to output's stringByReplacingOccurrencesOfString:("(?<=[Ee])") ¬
withString:("+") options:(regex) range:({0, output's |length|()})
end if
end if
return output as text -- Return as AppleScript text.
Line 566 ⟶ 586:
(my incrementNumericalString:"12345" byAmount:1), ¬
(my incrementNumericalString:"999,999,999,999,999" byAmount:5), ¬
(my incrementNumericalString:"-1.23234" byAmount:10 localeID:"en"), ¬
(my incrementNumericalString:"-1,23E234E+01" byAmount:"10" localeID:"fr_FR"), ¬
(my incrementNumericalString:"-1.234 x 10^1" byAmount:"10") ¬
}</syntaxhighlight>
 
{{output}}
(On a machine configured for "en_GB".)
<syntaxhighlight lang="applescript">{"12346", "1,000,000,000,000,004", "8.77", "8,77E+0"}</syntaxhighlight>
<syntaxhighlight lang="applescript">{"12346", "1,000,000,000,000,004", "8.766", "-2,34E+0", "-2.34 x 10^0"}</syntaxhighlight>
 
=={{header|ARM Assembly}}==
557

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.