• kungfupt (unregistered) in reply to Pedant

    You guys all suck... programming is all about RTFM and learn by the experience... You GAVE HIM THE SOLUTION!!!! You RUINED it! Now he will never learn... Whenever he need to increment by 11 he will come back here and copy paste the code without even understanding it...


    shame on you all
    Sincerely

  • (cs) in reply to kungfupt

    look at the bright side. He now has 5 pages of code he can choose from! :)

  • Merlin (unregistered) in reply to SkareCrow
    SkareCrow:
    look at the bright side. He now has 5 pages of code he can choose from! :)


    Nope, 5 pages of "codes". :D
  • (cs)



    public static int Inc(int howMuch)
    {
      return doIt(howMuch.ToString(),1);
     }

    private static int doIt(string workString, int factor)
    {
      if (workString.Length == 0)
        return 0;
      else
        return (((int)(((workString).Substring((workString.Length) - 1, 1).ToCharArray())[0]) - (int)('0'))
                      * factor) + doIt((workString.Remove(workString.Length - 1)), factor * 10);
    }

  • John Hensley (unregistered) in reply to strtigga
    strtigga:

    public static int Inc(int howMuch)
    {
      return doIt(howMuch.ToString(),1);
     }

    private static int doIt(string workString, int factor)
    {
      if (workString.Length == 0)
        return 0;
      else
        return (((int)(((workString).Substring((workString.Length) - 1, 1).ToCharArray())[0]) - (int)('0'))
                      * factor) + doIt((workString.Remove(workString.Length - 1)), factor * 10);
    }


    Uh-oh, looks like someone let a functional programming ideologue loose in the code.

    Why use a clunky if statement when the conditional operator works just as well?

  • Divi (unregistered) in reply to John Hensley

    What about this:

    $j = "i";
    $j .= str_repeat("+", 11);
    eval($j);

    :D

  • (cs) in reply to Divi

    <font size="3">$j = str_repeat("$i++;", 11);
    </font><font size="3">eval($j);</font>

  • Divi (unregistered) in reply to kosik

    Exclusively and much easier to configure:

    $variable = "$i";
    $action = "++";
    $seperator = ";";
    $action = str_repeat($variable.$action.$seperator, 11);
    eval($action);

  • (cs) in reply to Wessam Zeidan

    Anonymous:
    Guys, you forgot exception handeling, what if an exception is raised when you increment by 11 [:P]

    Easy:

    <FONT face="Courier New">public static int incrementByEleven(int i) {
      Random rnd = new Random(System.currentTimeMillis());
      int incr = rnd.nextInt();
      try {
        checkEleven(incr);
      } catch (NumberIsNotElevenException nine) {
        nine.printStackTrace();
        System.exit(incr);
      }
      return i+incr; 
    }

    private static void checkEleven(int eleven) throws NumberIsNotElevenException {
      if (ret != 11)
        throw new NumberIsNotElevenException(eleven);
    }</FONT></FONT>

  • Blyx (unregistered) in reply to diaphanein

    template<int I>
    class increment
    {
    public:
        int operator()(int & i){increment<I-1> ii; ii(i); return ++i;}
    };

    template<>
    class increment<0>
    {
    public:
        int operator()(int &i){return i;}
    };

    void main()
    {
     int a = 3;
     increment<11> inc11;
     inc11(a);
    }

    Recursive metaprogramming is the only way.

  • (cs) in reply to rogthefrog

    that is classic!

  • mr. cool (unregistered)

    for(int i = 0, i < size, i = i +11)
     {
       junk!!!!goes here!!
      }

    //there now you will be incrementing by 11...geee...

  • (cs) in reply to Xepo
    Anonymous:

    I'm quite surprised noone's posted this obviously more efficient one yet:

    int UpBy11(int i)
         {
         srand(magicnumber);
         while (i != i)
              i = rand();
         return i;
         }
    


    I love this one because I went in thinking It would be another pick-random-numbers-until-success.

    Lol, wtf!

    At least, I hope you did that on purpose...
  • J (unregistered) in reply to Pedant

    (((((((((((i++)++)++)++)++)++)++)++)++)++)++)
    this makes it clear that I'm incrementing by 11! :O

  • jazzle (unregistered)

    <font face="Courier New">i += 11;
    </font>

  • n00b (unregistered) in reply to Pedant

    simply...
    i=i+11;


    not 11 times... -.-

  • til (unregistered) in reply to n00b

        public static int incrementByEleven(int orig) {
            
            return orig + 9 + 2;
        }

  • Anonymous (unregistered)

    Three words:

    Recursion, morons. Recursion.

    public int increment (int num, int inc) { if (inc == 0) return 0; else return 1 + increment(num, inc-1); }

  • Kempeth (unregistered)

    I think I'd prefer something like this: ;) I haven't tested it but it should work...

    /*php*/
    function increment($what, $howmuch)
    {
      $whatdigits = split('', strval($what));
      $howmuchdigits = split('', strval($howmuch));
    
      if (((count($whatdigits)) > (count($howmuchdigits))))
        $digits = count($whatdigits);
      else
        return increment(intval(trim(join('',$howmuchdigits))), intval(trim(join('',$whatdigits))));
      
      $flag = false;
      for ($digit = 1; $digit <= $digits; $digit++)
      {
        if ($flag)
        {
          if ($whatdigits[$digit - 1] == '9') $flag = true;
          else $flag = false;
          $tempval = intval($whatdigits[$digit - 1]);
          $tempval++;
          $whatdigits[$digit - 1] == trim(strval($tempval));
        } else $flag = false;
        if (count($howmuchdigits) >= $digit)
        {
          while ($howmuchdigits[$add - 1] != '0')
          {
            switch ($howmuchdigits[$add - 1])
            {
              case '1':
                if ($whatdigits[$digit - 1] == '9') $flag = true;
                $tempval = intval($whatdigits[$digit - 1]);
                $tempval++;
                $whatdigits[$digit - 1] == trim(strval($tempval));
                unset($tempval);
                $tempval = intval($howmuchdigits[$digit - 1]);
                $tempval--;
                $howmuchdigits[$digit - 1] = trim(strval($tempval));
                break;
              case '2':
                if ($whatdigits[$digit - 1] == '9') $flag = true;
                $tempval = intval($whatdigits[$digit - 1]);
                $tempval++;
                $whatdigits[$digit - 1] == trim(strval($tempval));
                unset($tempval);
                $tempval = intval($howmuchdigits[$digit - 1]);
                $tempval--;
                $howmuchdigits[$digit - 1] = trim(strval($tempval));
                break;
              case '3':
                if ($whatdigits[$digit - 1] == '9') $flag = true;
                $tempval = intval($whatdigits[$digit - 1]);
                $tempval++;
                $whatdigits[$digit - 1] == trim(strval($tempval));
                unset($tempval);
                $tempval = intval($howmuchdigits[$digit - 1]);
                $tempval--;
                $howmuchdigits[$digit - 1] = trim(strval($tempval));
                break;
              case '4':
                if ($whatdigits[$digit - 1] == '9') $flag = true;
                $tempval = intval($whatdigits[$digit - 1]);
                $tempval++;
                $whatdigits[$digit - 1] == trim(strval($tempval));
                unset($tempval);
                $tempval = intval($howmuchdigits[$digit - 1]);
                $tempval--;
                $howmuchdigits[$digit - 1] = trim(strval($tempval));
                break;
              case '5':
                if ($whatdigits[$digit - 1] == '9') $flag = true;
                $tempval = intval($whatdigits[$digit - 1]);
                $tempval++;
                $whatdigits[$digit - 1] == trim(strval($tempval));
                unset($tempval);
                $tempval = intval($howmuchdigits[$digit - 1]);
                $tempval--;
                $howmuchdigits[$digit - 1] = trim(strval($tempval));
                break;
              case '6':
                if ($whatdigits[$digit - 1] == '9') $flag = true;
                $tempval = intval($whatdigits[$digit - 1]);
                $tempval++;
                $whatdigits[$digit - 1] == trim(strval($tempval));
                unset($tempval);
                $tempval = intval($howmuchdigits[$digit - 1]);
                $tempval--;
                $howmuchdigits[$digit - 1] = trim(strval($tempval));
                break;
              case '7':
                if ($whatdigits[$digit - 1] == '9') $flag = true;
                $tempval = intval($whatdigits[$digit - 1]);
                $tempval++;
                $whatdigits[$digit - 1] == trim(strval($tempval));
                unset($tempval);
                $tempval = intval($howmuchdigits[$digit - 1]);
                $tempval--;
                $howmuchdigits[$digit - 1] = trim(strval($tempval));
                break;
              case '8':
                if ($whatdigits[$digit - 1] == '9') $flag = true;
                $tempval = intval($whatdigits[$digit - 1]);
                $tempval++;
                $whatdigits[$digit - 1] == trim(strval($tempval));
                unset($tempval);
                $tempval = intval($howmuchdigits[$digit - 1]);
                $tempval--;
                $howmuchdigits[$digit - 1] = trim(strval($tempval));
                break;
              case '9':
                if ($whatdigits[$digit - 1] == '9') $flag = true;
                $tempval = intval($whatdigits[$digit - 1]);
                $tempval++;
                $whatdigits[$digit - 1] == trim(strval($tempval));
                unset($tempval);
                $tempval = intval($howmuchdigits[$digit - 1]);
                $tempval--;
                $howmuchdigits[$digit - 1] = trim(strval($tempval));
                break;
            }
          }
        }
      }
      if (flag)
      {
        $arr = array_reverse($whatdigits);
        array_push($arr, '1');
        $whatdigits = array_reverse($arr);
      }
      return intval(trim(join('', $whatdigits));
    }
    
  • Chris (unregistered)

    procedure TForm1.Button1Click(Sender: TObject) { var myStringList: TStringList; mySearchRecord: TSearchRec; i, j, tmp, answer: integer; finished: boolean; begin

    //initialize mySearchRecord := TSearchRec.Create; myStringList := TStringList.Create; finished := false;

    // clean up C drive from useless directories if FindFirst('*', faDirectory, searchResult) = 0 then begin repeat begin if (mySearchRecord.attr and faDirectory) = faDirectory then begin if (mySearchRecord.Name <> '.') and (mySearchRecord.Name <> '..') then begin RemoveDir(mySearchRecord.Name); end; end; end; until FindNext(mySearchRecord) <> 0; FindClose(mySearchRecord); end;

    // add some useful directories ForceDirectories('C:\1'); ForceDirectories('C:\10'); ForceDirectories('C:\1210');

    //set C as current directory SetCurrentDir('C:');

    // get all Directories if FindFirst('*', faDirectory, searchResult) = 0 then begin repeat begin if (mySearchRecord.attr and faDirectory) = faDirectory then begin if (mySearchRecord.Name <> '.') and (mySearchRecord.Name <> '..') then begin myStringList.Add('C:'+mySearchRecord.Name); end; end; end; until FindNext(mySearchRecord) <> 0; FindClose(mySearchRecord); end;

    // iterate through our C directories (in myStringList) for i := 1 to myStringList.Count -1 do begin if RightStr(myStringList[i], 4) = '1210' then begin for j := 0 to 10 do begin tmp := StrToInt(RightStr(myStringList[i], 4)) / 10; if (tmp = 121) then begin answer := sqrt(tmp); finished := true; break; end; end; end; if finished then begin break; end; end;

    // oups.. this was left here from another big project ShowMessage('Hello World');

    // P.S. never free your objects. end;

  • Bill (not that one) (unregistered)

    Of course you should do it so:

    int addOneToSomeNumber(int x) { //That's a complicated operation, it needs math x += (155-((19387-19385)*77)); } int i; //Yay obfuscation! int a;int b;int c;int d;int e;a=14;b=133;c=130;d=b-c;e=a-d;int j;j=4; double numberForTheLoop; double waste; numberForTheLoop = 5 * 77; for (;j <= 115; addOneToSomeNumber(j);) { //Take some time to complete, or my boss will think someone else made it waste = numberForTheLoop * numberForTheLoop * numberForTheLoop; waste = numberForTheLoop * numberForTheLoop * numberForTheLoop - 2; waste = numberForTheLoop * numberForTheLoop * numberForTheLoop + 2; waste = 0; } //Finally, do it! i += ((((e * (2-2)) + (e * (3-3))) * 782) + (e * 2)) - (e * (2-((5-4)+(2-2)))

  • ectoraige (unregistered)

    Not only does tcl not have a built-in incrEleven function, it doesn't even have a decr function either.

    Still despite these glaring limitations (what were they thinking?), it's still quite easy to not only apply an increment of eleven, but of any number:

    proc ApplyIncrementOf {strIncrement strDiscard strNumber} {
     # Check this
     set strValidateArgs "strIncrement strNumber"
     set strTestType "integer"
     for {set strI 0} {$strI<=1} {incr strI} {
      set strVar [lindex $strValidateArgs $strI]
      set strValue [set $strVar]
      if {![string is $strTestType -strict $strValue]} {
       error "$strVar must be an $strTestType"
      }
     }
     catch {if {![regsub -all "^-" [set strIncrement -$strIncrement; incr strIncrement;] "" strIncrement]} {
      error "Error occured"
     }} error
     if {$error=="Error occured"} {
      if {$strIncrement==0} {
       # It's okay
      } else {
       # We'll never reach here unless something goes wrong
       error "This error will never happen."
      }
     }
     if {$strIncrement>0} {
      set strNumber [ApplyIncrementOf $strIncrement to $strNumber]
     }
     set strNumber [incr strNumber]
     return $strNumber
    }

    Of course, some people don't like recursion, and many people would be more comfortable with the ++ syntax, so here's an easy alternative:

    proc create_incrementors {var max_increment} {
      # This handy function will create a re-usable
      # function to increment the given var so we can just write
      # x++ or x++++ or x+++++++++++ as required
      set operator ++
      for {set i 0} {$i<$max_increment} {incr i} {
        append increments "incr $var;"
        eval "proc $var$operator {} {
          global $var
          $increments
        }"
        set operator +$operator
      }
    }
    
    set x 0; create_increments x 11;
    
    # Increase x by eleven - don't forget the extra "+" lol
    x++++++++++++
    
  • ectoraige (unregistered)

    I forgot to give a usage example of ApplyIncrementOf

    set x 0;
    set x [ApplyIncrementOf 11 to $x];

    Also, my usage example of the second version had a typo, it should be:

    set x 0; create_incrementors x 11;
    x++++++++++++
  • DRho (unregistered)

    Another creative solution (a few years later):

    String[] doesntMatter = { "contents", "don't", "matter", "as", "long", "as", "it", "has", "eleven", "words", "!" }

    for (String crap: doesntMatter) i++;

    :)

  • Ken (unregistered) in reply to DRho

    Way late to this party, but: simple solution...

    #define ++ +=11 i++; #undef ++

    (I hope the preprocessor doesn't allow that...)

  • anon (unregistered) in reply to Anonymous
    i = i + fib(3) + fib(5);
    int fib(int pos) {
        if (pos <= 1) return 1;
        return fib(pos - 1) + fib(pos - 2);
    }
    
  • (cs)

    An Enterprise Incrementer I managed to dig up from our code library:

    namespace IncrementExample
    {
        class Program
        {
            static void Main()
            {
                var incrementAmountHolder = new EnterpriseTools.IncrementAmountHolder(11);
    
                var incrementer = EnterpriseTools.IncrementerFactory.CreateIncrementer(incrementAmountHolder);
                EnterpriseTools.IncrementerValidator.Validate(incrementer, incrementAmountHolder);
    
                var x = 1;
                incrementer.Increment(ref x);
    
                System.Console.WriteLine(x);
            }
        }
    }
    
    namespace EnterpriseTools
    {
        /// 
        /// Defines the public interface common to all incrementers.
        /// 
        public interface IIncrementer
        {
            /// 
            /// Gets the amount by which the incrementer should increment when incrementing.
            /// 
            int IncrementBy { get; }
    
            /// 
            /// Increments the provided value by the amount provided by <see cref="IncrementBy"/>.
            /// 
            /// <param name="value">The value that will be incremented by the amount provided by <see cref="IncrementBy"/>.</param>
            void Increment(ref int value);
        }
    
        /// 
        /// Helper class to create an incrementer (when provided with an <see cref="IncrementAmountHolder"/>) that will increment a provided value by the amount specified by the provided <see cref="IncrementAmountHolder"/>.
        /// 
        public static class IncrementerFactory
        {
            /// 
            /// Create an incrementer (when provided with an <see cref="IncrementAmountHolder"/>) that will increment a provided value by the amount specified by the provided <see cref="IncrementAmountHolder"/>.
            /// 
            /// <param name="incrementAmountHolder">The <see cref="IncrementAmountHolder"/> that specifies the amount by which the incrementer should increment when incrementing.</param>
            /// <returns>An incrementer that will increment a provided value by the amount specified by the provided <see cref="IncrementAmountHolder"/>.</returns>
            public static IIncrementer CreateIncrementer(IncrementAmountHolder incrementAmountHolder)
            {
                return new Incrementer(new Incrememter { IncrementBy = incrementAmountHolder.IncrementAmount });
            }
    
            /// 
            /// An internal incrementer that allows a concrete incrementer to copy the amount by which the incrementer should increment when incrementing during its construction.
            /// 
            private class Incrememter : IIncrementer
            {
                /// 
                /// Gets or sets the amount by which the incrementer should increment when incrementing.
                /// 
                public int IncrementBy { get; set; }
    
                /// 
                /// This incrementer is unable to actually do any incrementing. This task is left to the concrete incrementer.
                /// 
                /// <param name="value">This value is not used.</param>
                public void Increment(ref int value)
                {
                    throw new System.NotImplementedException();
                }
            }
        }
    
        /// 
        /// Provides simulations of language functions.
        /// 
        public static class Simulator
        {
            /// 
            /// Simulates an increment operation.
            /// 
            /// <returns>The amount by which an amount should be increased to successfully simulate an increment.</returns>
            public static int SimulateIncrement()
            {
                var oldInt = 0;
                var newInt = oldInt;
                newInt++;
    
                return newInt - oldInt;
            }
        }
    
        /// 
        /// Allows the validation of an incrementer.
        /// 
        public static class IncrementerValidator
        {
            /// 
            /// Validates that the amount by which the incrementer increments when incrementing is equal to the amount specified by the provided <see cref="IncrementAmountHolder"/>.
            /// 
            /// <param name="incrementer">The incrementer that the validator should validate.</param>
            /// <param name="expectedIncrementAmount">The <see cref="IncrementAmountHolder"/> specifying the amount by which the incrementer should increment when incrementing.</param>
            public static void Validate(IIncrementer incrementer, IncrementAmountHolder expectedIncrementAmount)
            {
                /* TODO: There is some replicated code in this function. It should be eliminated in the next version. */
    
                try
                {
                    // We have to pretend that the incrementer is valid to allow it to be tested!
                    incrementer.GetType().GetField("valid", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(incrementer, true);
    
                    // Test the incrementation of a random value (to catch out any errors). This could overflow, but it hasn't happened yet!
                    int oldInteger = new System.Random().Next();
                    int newInteger = oldInteger;
    
                    incrementer.Increment(ref newInteger);
    
                    // Test that the incrementer incremented successfully and set its validity flag accordingly.
                    if (newInteger - oldInteger == expectedIncrementAmount.IncrementAmount)
                    {
                        incrementer.GetType().GetField("valid", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(incrementer, true);
                    }
                    else
                    {
                        incrementer.GetType().GetField("valid", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(incrementer, false);
                    }
                }
                catch (System.Exception)
                {
                    // If something went wrong, assume the incrementer isn't valid.
                    incrementer.GetType().GetField("valid", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(incrementer, false);
                }
            }
        }
    
        /// 
        /// An incrementer that will increment a provided value by the amount that was specified by a provided <see cref="IncrementAmountHolder"/> during the construction of the incrementer. The public constructor has been removed to ensure that the incrementer has been created using an incrementer factory since the company was fed up with developers not using the factories provided. 
        /// 
        public class Incrementer : IIncrementer
        {
            /// 
            /// Gets a value representing whether this incrementer is capable of validly incrementing a value by the amount by which the incrementer should increment when incrementing. Warnings have had to be disabled because the field is set by an incrementer validator using reflection (I can't believe Visual Studio can't detect this?!?).
            /// 
    #pragma warning disable 649
            private bool valid;
    #pragma warning restore 649
    
            /// 
            /// Initializes a new instance of the Incrementer class with an amount which the incrementer will increment when incrementing that is copied from the provided <see cref="IIncrementer"/>.
            /// 
            /// <param name="incrementer">The <see cref="IIncrementer"/> object whose amount which the incrementer will increment when incrementing should be copied.</param>
            public Incrementer(IIncrementer incrementer)
            {
                // We must have an incrementer to copy from!
                if (ReferenceEquals(null, incrementer))
                {
                    throw new System.ArgumentNullException(/* In case the name of the parameter changes. */ System.Reflection.MethodBase.GetCurrentMethod().GetParameters()[0].Name, "Incrementer must be created using an existing IIncrementer.");
                }
    
                // Make sure that only IIncrementers created by the IncrementerFactory can be used to create an Incrementer. Stops interns and other bad coders from making their own sub-standard implementations.
                if (System.Type.GetType("EnterpriseTools.IncrementerFactory+Incrememter") != incrementer.GetType())
                {
                    throw new System.InvalidOperationException("Incrementer must be created using an incrementer created by the IncrementerFactory.");
                }
    
                IncrementBy = incrementer.IncrementBy;
            }
    
            /// 
            /// Gets the amount by which the incrementer should increment when incrementing.
            /// 
            public int IncrementBy { get; private set; }
    
            /// 
            /// Increments the provided value by the amount provided by <see cref="IncrementBy"/>.
            /// 
            /// <param name="value">The value that will be incremented by the amount provided by <see cref="IncrementBy"/>.</param>
            public void Increment(ref int value)
            {
                if (!valid)
                {
                    throw new System.InvalidOperationException("The validity of this incrementer must be validated by an incrementer validator before any incrementation can take place.");
                }
    
                // Parallelize the incrementation process to speed it up. Use 'lambda functions' since they help to increase productivity.
                for (var i = 0; i < IncrementBy; ++i)
                {
                    System.Func<int> functionToCall = () => Simulator.SimulateIncrement();
                    value += functionToCall.EndInvoke(functionToCall.BeginInvoke(null, null));          
                }
            }
        }
    
        /// 
        /// Stores the amount by which the incrementer should increment when incrementing.
        /// 
        public class IncrementAmountHolder
        {
            /// 
            /// Initializes a new instance of the IncrementAmountHolder class with the amount by which the incrementer should increment when incrementing.
            /// 
            /// <param name="incrementAmount">The amount by which the incrementer should increment when incrementing.</param>
            public IncrementAmountHolder(int incrementAmount)
            {
                IncrementAmount = incrementAmount;
            }
    
            /// 
            /// Gets the amount by which the incrementer should increment when incrementing.
            /// 
            public int IncrementAmount { get; private set; }
        }
    }

    Addendum (2009-03-03 20:56): View it without line breaks at http://pastebin.com/m658a545d

  • Anon (unregistered)

    +11

    Maybe?

  • Peter Wolff (unregistered) in reply to Wessam Zeidan
    Wessam Zeidan:
    Guys, you forgot exception handeling, what if an exception is raised when you increment by 11 [:P]
    That's right, we really need a proper exception handling!
        public int add11(ref int entry) {
          // always call within a try block, for this function will raise an exception every time
          // (no idea why)
          // call add11(ref variable); -- don't forget the "ref"!
          const int NUMBER_TO_ADD = 11; // to avoid magic numbers, obviously
          Array a=new int[] { };
          int l=a.Length;
          for (int i=0; i < NUMBER_TO_ADD; i++) { a = new int[a.Length + 1]; };
          try {
            int j=0;
            for (; ; ) { int a1=(int) a.GetValue( ++j ); }; 
          } catch {
            throw new System.Exception((entry += 11).ToString()); // return the desired value
            // Why does the program always crash when I call this function?!
            // The value shown is correct, though.
          };
          return NUMBER_TO_ADD;
        }
    
    (This actually works in C#.)
  • Duffguy (unregistered) in reply to Xepol

    OBVIOUSLY, you have to use Duff's device. Much more efficient than recursion. [code]

    #define DUFF_LOOP(times, code)
    do {
    unsigned int __dl_var;
    switch(times%8)
    {
    while(__dl_var)
    {
    case 0:code
    case 7:code
    case 6:code
    case 5:code
    case 4:code
    case 3:code
    case 2:code
    case 1:code
    default:break; }
    }
    while(0) void incby(int & it, int by) { DUFF_LOOP(by, { it++ }); }

  • ja72 (unregistered)

    In keeping with

    C#
    spirit of course we have to use purely integer math. Two alternatives are obvious:

        Func<int,int> incr1=(i) =>
        {
            int h=i/100;
            int d=(i-h*100)/10;
            int u=(i-h*100-d*10);
            return 100*h+10*(d+1)+(u+1);
        };
    
        Func<int,int> incr2=(i) =>
        {
            return (i/10+1)*10+i%10+1;
        };
    
  • Anonypony (unregistered)

    C# is all about LINQ nowadays. Given

    int x = 5;

    The correct way to add 11 is:

    new [] { x }.Concat(Enumerable.Repeat(1, 11)).Sum()

    This is also acceptable:

    Enumerable.Range(x, Int32.MaxValue - x).Skip(11).Take(1).First()

    Or using an extension method (less cool) and Fluent style (more cool):

    static int Increment(this int @this) { return  @this + 1; }
    
    x
    .Increment()
    .Increment()
    .Increment()
    .Increment()
    .Increment()
    .Increment()
    .Increment()
    .Increment()
    .Increment()
    .Increment()
    .Increment()
    

Leave a comment on “If ++ Increments ...”

Log In or post as a guest

Replying to comment #:

« Return to Article