A couple of years ago, my friend wanted to learn programming, so I was giving her a hand with resources and reviewing her code. She got to the part on adding code comments, and wrote the now-infamous line,

i = i + 1 #this increments i

We’ve all written superflouous comments, especially as beginners. And it’s not even really funny, but for whatever reason, somehow we both remember this specific line years later and laugh at it together.

Years later (this week), to poke fun, I started writing sillier and sillier ways to increment i:

Beginner level:

# this increments i:
x = i 
x = x + int(True)
i = x

Beginner++ level:

# this increments i:
def increment(val):
   for i in range(val+1):
      output = i + 1
   return output

Intermediate level:

# this increments i:
class NumIncrementor:
	def __init__(self, initial_num):
		self.internal_num = initial_num

	def increment_number(self):
		incremented_number = 0
		# we add 1 each iteration for indexing reasons
		for i in list(range(self.internal_num)) + [len(range(self.internal_num))]: 
			incremented_number = i + 1 # fix obo error by incrementing i. I won't use recursion, I won't use recursion, I won't use recursion

		self.internal_num = incremented_number

	def get_incremented_number(self):
		return self.internal_num

i = input("Enter a number:")

incrementor = NumIncrementor(i)
incrementor.increment_number()
i = incrementor.get_incremented_number()

print(i)

Since I’m obviously very bored, I thought I’d hear your take on the “best” way to increment an int in your language of choice - I don’t think my code is quite expert-level enough. Consider it a sort of advent of code challenge? Any code which does not contain the comment “this increments i:” will produce a compile error and fail to run.

No AI code pls. That’s no fun.

  • Azzu@lemm.ee
    link
    fedilink
    arrow-up
    0
    ·
    edit-2
    12 days ago
    int toIncrement = ...;
    int result;
    do {
      result = randomInt();
    } while (result != (toIncrement + 1));
    print(result);
    
    • Ace@feddit.ukOP
      link
      fedilink
      arrow-up
      0
      ·
      edit-2
      12 days ago

      but if i gets randomly bitflipped, wouldn’t i != i+1 still be false? It would have to get flipped at exactly the right time, assuming that the cpu requests it from memory twice to run that line? It’d probably be cached anyway.

      I was thinking you’d need to store the original values, like x=i and y=i+1 and while x != y etc… but then what if x or y get bitflipped? Maybe we hash them and keep checking if the hash is correct. But then the hash itself could get bitflipped…

      Thinking too many layers of redundancy deep makes my head hurt. I’m sure there’s some interesting data integrity computer science in there somewhere…

  • Eager Eagle@lemmy.world
    link
    fedilink
    English
    arrow-up
    0
    ·
    12 days ago

    That’s a tricky problem, I think you might be able to create a script that increments it recursively.

    I’m sure this project that computes Fibonacci recursively spawning several docker containers can be tweaked to do just that.

    https://github.com/dgageot/fiboid

    I can’t think of a more efficient way to do this.

    • palordrolap@fedia.io
      link
      fedilink
      arrow-up
      0
      ·
      11 days ago

      This is actually the correct way to do it in JavaScript, especially if the right hand side is more than 1.

      If JavaScript thinks i contains a string, and let’s say its value is 27, i += 1 will result in i containing 271.

      Subtraction doesn’t have any weird string-versus-number semantics and neither does unary minus, so i -=- 1 guarantees 28 in this case.

      For the increment case, ++ works properly whether JavaScript thinks i is a string or not, but since the joke is to avoid it, here we are.

  • Sonotsugipaa@lemmy.dbzer0.com
    link
    fedilink
    English
    arrow-up
    0
    ·
    12 days ago
    // C++20
    
    #include <concepts>
    #include <cstdint>
    
    template <typename T>
    concept C = requires (T t) { { b(t) } -> std::same_as<int>; };
    
    char b(bool v) { return char(uintmax_t(v) % 5); }
    #define Int jnt=i
    auto b(char v) { return 'int'; }
    
    // this increments i:
    void inc(int& i) {
      auto Int == 1;
      using c = decltype(b(jnt));
      i += decltype(jnt)(C<decltype(b(c))>);
    }
    

    I’m not quite sure it compiles, I wrote this on my phone and with the sheer amount of landmines here making a mistake is almost inevitable.

    • Ace@feddit.ukOP
      link
      fedilink
      arrow-up
      0
      ·
      edit-2
      12 days ago

      I got gpt to explain this and it really does not like this code haha

      It also said multiple times that c++ won’t allow the literal string ‘int’? I would be surprised if that’s true. A quick search has no relevant results so probably not true.

      • Sonotsugipaa@lemmy.dbzer0.com
        link
        fedilink
        English
        arrow-up
        0
        ·
        12 days ago

        It’s funny that it complains about all of the right stuff (except the ‘int’ thing), but it doesn’t say anything about the concept.

        About the ‘int’ literal (which is not a string): cppreference.com has a description on this page about it, ctrl+f “multicharacter literal”.

        • Sonotsugipaa@lemmy.dbzer0.com
          link
          fedilink
          English
          arrow-up
          0
          ·
          12 days ago

          Multiple-character char literals evaluate as int, with implementation defined values - it is extremely unreliable, but that particular piece of code should work.

  • Björn Tantau@swg-empire.de
    link
    fedilink
    arrow-up
    0
    ·
    edit-2
    12 days ago

    Everything is easier in PHP!

    <?php
    
    /**
     * This increments $i
     * 
     * @param int $i The number to increment.
     *
     * @return int The incremented number.
     */
    function increment(int $i) {
      $factor = 1;
      $adjustment = 0;
      if ($i < 0) {
        $factor *= -1;
        $adjustment = increment(increment($adjustment));
      }
      $i *= $factor;
      $a = array_fill(1, $i, 'not_i');
      if ($i === 0) {
        array_push($a, 'not_i');
      }
      array_push($a, $i);
      return array_search($i, $a, true) * $factor + $adjustment;
    }
    
  • dont_lemmee_down@lemm.ee
    link
    fedilink
    arrow-up
    0
    ·
    12 days ago

    Create a python file that only contains this function

    def increase_by_one(i):
        # this increments i
        f=open(__file__).read()
        st=f[28:-92][0]
        return i+f.count(st)
    

    Then you can import this function and it will raise an index error if the comment is not there, coming close to the most literal way

    Any code which does not contain the comment “this increments i:” will produce a compile error and fail to run.

    could be interpreted in python

  • Admiral Patrick@dubvee.org
    link
    fedilink
    English
    arrow-up
    0
    ·
    12 days ago
    // this increments i:
    
    function increment(val:number): number {
      for (let i:number = 1; i <= 100; i = i +1) {
        val = val + 0.01
      }
    
      return Math.round(val)
    }
    
    
    let i = 100
    i = increment(i)
    // 101
    
    • Susaga@sh.itjust.works
      link
      fedilink
      English
      arrow-up
      0
      ·
      12 days ago

      This should get bonus points for incrementing i by 1 as part of the process for incrementing i by 1.