DEV Community

Discussion on: Daily Challenge #260 - Subtract the Sum

Collapse
 
pinotattari profile image
Riccardo Bernardini • Edited

Ada solution

with Ada.Strings.Unbounded;              use Ada.Strings.Unbounded;

subtype Parameter_Type is Integer range 10 .. 9999; 

subtype Fruit_Index is Integer range 1 .. 100;

Names : array(Fruit_Index) of Unbounded_String  := 
    ( 
-- Fill with names
     );

function SubctractSum(N : Parameter_Type)  return Unbounded_String
is (if N in Fruit_Index then Names(N) else "apple");

-- Explanation: 
-- N can be written as 
--
--       N = a*1000 + b*100 + c*10 + d 
--
-- if N <= 100, we access directly the name array.  
--
-- If N > 100 (which means b >= 1) the new N is
--
--       New_N = a*1000 + b*100 + c*10 + d - (a+b+c+d)
--                     = a*999 + b*99 + c*9
--
-- If the iteration stops with New_N it must be 
--  New_N <= 100 which implies a = 0,  b=1 
-- (it cannot be b=0 otherwise we would had 
-- not done another iteration) and c=0, that is,  
-- New_N = 99.
--
-- Therefore, unless N<=100, the result is "apple"