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.

  • Admiral Patrick@dubvee.org
    link
    fedilink
    English
    arrow-up
    12
    ·
    edit-2
    4 days ago
    // this increments i:
    // Version 2: Now more efficient; only loops to 50 and just rounds up.  That's 50% less inefficient!
    
    function increment(val:number): number {
      for (let i:number = 0; i < 50; 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
      12
      ·
      4 days ago

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

      • Admiral Patrick@dubvee.org
        link
        fedilink
        English
        arrow-up
        1
        ·
        edit-2
        4 days ago

        I tried to make the afterthought that increments the loop counter use the increment function recursively, but Javascript said no lol.

  • notabot@lemm.ee
    link
    fedilink
    arrow-up
    24
    ·
    4 days ago

    Trying to avoid using any arithmetic operators, and sticking just to binary (extending beyond 16 bit unsigned ints is left as an exercise for the interested reader):

    #!/usr/bin/perl
    
    # This increments $i
    
    my $i=1;
    print "Start: $i ";
    
    if (($i & 0b1111111111111111) == 0b1111111111111111) {die "Overflow";}
    if (($i & 0b0000000000000001) == 0b0000000000000000) {$i=(($i & 0b1111111111111110) | 0b0000000000000001);}
    else
    {
            if (($i & 0b0111111111111111) == 0b0111111111111111) {$i=(($i & 0b0000000000000000) | 0b1000000000000000);}
            if (($i & 0b0011111111111111) == 0b0011111111111111) {$i=(($i & 0b1000000000000000) | 0b0100000000000000);}
            if (($i & 0b0001111111111111) == 0b0001111111111111) {$i=(($i & 0b1100000000000000) | 0b0010000000000000);}
            if (($i & 0b0000111111111111) == 0b0000111111111111) {$i=(($i & 0b1110000000000000) | 0b0001000000000000);}
            if (($i & 0b0000011111111111) == 0b0000011111111111) {$i=(($i & 0b1111000000000000) | 0b0000100000000000);}
            if (($i & 0b0000001111111111) == 0b0000001111111111) {$i=(($i & 0b1111100000000000) | 0b0000010000000000);}
            if (($i & 0b0000000111111111) == 0b0000000111111111) {$i=(($i & 0b1111110000000000) | 0b0000001000000000);}
            if (($i & 0b0000000011111111) == 0b0000000011111111) {$i=(($i & 0b1111111000000000) | 0b0000000100000000);}
            if (($i & 0b0000000001111111) == 0b0000000001111111) {$i=(($i & 0b1111111100000000) | 0b0000000010000000);}
            if (($i & 0b0000000000111111) == 0b0000000000111111) {$i=(($i & 0b1111111110000000) | 0b0000000001000000);}
            if (($i & 0b0000000000011111) == 0b0000000000011111) {$i=(($i & 0b1111111111000000) | 0b0000000000100000);}
            if (($i & 0b0000000000001111) == 0b0000000000001111) {$i=(($i & 0b1111111111100000) | 0b0000000000010000);}
            if (($i & 0b0000000000000111) == 0b0000000000000111) {$i=(($i & 0b1111111111110000) | 0b0000000000001000);}
            if (($i & 0b0000000000000011) == 0b0000000000000011) {$i=(($i & 0b1111111111111000) | 0b0000000000000100);}
            if (($i & 0b0000000000000001) == 0b0000000000000001) {$i=(($i & 0b1111111111111100) | 0b0000000000000010);}
    }
    print "End: $i\n";
    
  • dont_lemmee_down@lemm.ee
    link
    fedilink
    arrow-up
    32
    ·
    4 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

    • Ace@feddit.ukOP
      link
      fedilink
      arrow-up
      6
      ·
      edit-2
      4 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…

      • charizardcharz@lemmy.world
        link
        fedilink
        arrow-up
        1
        ·
        4 days ago

        I didn’t really dig too deep into it. It might be interesting to see what it actually compiles to.

        From what I can remember result of i+1 would have to be stored before it can be compared thus it would be possible for i to experience a bit flip after the result of i+1 is stored.

      • psud@aussie.zone
        link
        fedilink
        arrow-up
        1
        ·
        4 days ago

        You just wait for the right bit too be flipped and the wrong ones flipped are flipped an even number of times

  • fool@programming.dev
    link
    fedilink
    arrow-up
    10
    ·
    2 days ago

    First, imagine a number in JavaScript. (Bit of a nail biter here, huh?)

    let i = 5
    

    Then, we will construct an incrementor. This is really simple: here is the method.

    1. Make a bracket-string-centric version of eval().
    []["filter"]["constructor"]("return i+1")()
    
    1. Reconstruct stringy eval() by using +[] as 0, +!+[] as 1, and implicit conversions as ways to create strings. For example, ‘false’ is (![]+[]), so ‘f’ is (![]+[])[+[]].
    [][
      (![] + [])[+[]] + // f
      ([![]] + [][[]])[+!+[] + [+[]]] + // i
      (![] + [])[!+[] + !+[]] + // l
      (!![] + [])[+[]] + // t
      (!![] + [])[!+[] + !+[] + !+[]] + // e
      (!![] + [])[+!+[]] // r
    ][
      ([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+ // c
      (!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+ // o
      ([][[]]+[])[+!+[]]+ // n
      (![]+[])[!+[]+!+[]+!+[]]+ // s
      (!![]+[])[+[]]+ // t
      (!![]+[])[+!+[]]+ // r
      ([][[]]+[])[+[]]+ // u
      ([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+ // c
      (!![]+[])[+[]]+ // t
      (!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+ // o
      (!![]+[])[+!+[]] // r
    ]("return i+1")()
    
    1. Draw the rest of the fucking owl. Final code:
    let i = 5; // haha yay
    
    [][
      (![] + [])[+[]] + // f
      ([![]] + [][[]])[+!+[] + [+[]]] + // i
      (![] + [])[!+[] + !+[]] + // l
      (!![] + [])[+[]] + // t
      (!![] + [])[!+[] + !+[] + !+[]] + // e
      (!![] + [])[+!+[]] // r
    ][
      ([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+ // c
      (!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+ // o
      ([][[]]+[])[+!+[]]+ // n
      (![]+[])[!+[]+!+[]+!+[]]+ // s
      (!![]+[])[+[]]+ // t
      (!![]+[])[+!+[]]+ // r
      ([][[]]+[])[+[]]+ // u
      ([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+ // c
      (!![]+[])[+[]]+ // t
      (!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+ // o
      (!![]+[])[+!+[]] // r
    ](
      (!![]+[])[+!+[]]+ // r
      (!![]+[])[!+[]+!+[]+!+[]]+ // e
      (!![]+[])[+[]]+ // t
      ([][[]]+[])[+[]]+ // u
      (!![]+[])[+!+[]]+ // r
      ([][[]]+[])[+!+[]]+ // n
      (+[![]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+!+[]]]+ // ' '
      ([![]]+[][[]])[+!+[]+[+[]]]+ // i
      (+(+!+[]+(!+[]+[])[!+[]+!+[]+!+[]]+[+!+[]]+[+[]]+[+[]])+[])[!+[]+!+[]]+ // +
      +!+[] // 1
    )()
    // no virus i swear. execute arbitrary code in your browser console.
    

    Anyway, that’s just everyday JS work. It’s like step 5 after resizing the button, but a bit before centering the div.

    based on this. some translation methods done differently.

  • calcopiritus@lemmy.world
    link
    fedilink
    arrow-up
    7
    ·
    4 days ago

    C:

    int increment(int i) {
        return (int) (1[(void*) i])
    

    However, if you wanna go blazingly fast you gotta implement O(n) algorithms in rust. Additionally you want safety in case of integer overflows.

    use std::error::Error;
    
    #[derive(Debug, Error)]
    struct IntegerOverflowError;
    
    struct Incrementor {
        lookup_table: HashMap<i32, i33>
    }
    
    impl Incrementor {
        fn new() -> Self {
            let mut lut = HashMap::new();
            for i in 0..i32::MAX {
                lut.insert(i, i+1)
            }
            Incrementor { lookup_table: lut }
        }
    
        fn increment(&self, i: i32) -> Result<i32, IntegerOverflowError> {
            self.lookup_table.get(i)
                .map(|i| *i)
                .ok_or(IntegerOverflowError)
    }
    

    On mobile so I don’t even know if they compile though.

  • letsgo@lemm.ee
    link
    fedilink
    English
    arrow-up
    10
    ·
    3 days ago

    C++:

    int i = 5;
    i ^= printf("The initial value of i is %d\n", i)^
    printf("i=i+1; // this increments i\n")^
    printf("Trigger very obscure FPU bug %c",(int)((float)8.5953287712*(double)8.5953287713-'?'))/10;
    printf("i has now been incremented by 1 : %d\n", i);
    

    Output:

    The initial value of i is 5  
    i=i+1; // this increments i  
    Trigger very obscure FPU bug  
    i has now been incremented by 1 : 6
    

    I didn’t test other values but they’re probably OK.

    • Eranziel@lemmy.world
      link
      fedilink
      arrow-up
      3
      ·
      edit-2
      2 days ago

      I didn’t test other values but they’re probably OK.

      Excellent work, thanks for the laugh.

    • palordrolap@fedia.io
      link
      fedilink
      arrow-up
      26
      ·
      4 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.

  • Eager Eagle@lemmy.world
    link
    fedilink
    English
    arrow-up
    9
    ·
    4 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.