Home > Software engineering >  Is it possible to simplify this algorithm so that it only uses 1 loop and 2 variables?
Is it possible to simplify this algorithm so that it only uses 1 loop and 2 variables?

Time:09-21

Is it possible to get the same results as this code using only a and b? I'm trying to calculate c from a and b to avoid using a third variable, but I can't find a solution.

#include <stdio.h>
#include <stdlib.h>

const int LENGTH = 20;

int main()
{
    char arr[LENGTH];

    for (int a = 0, b = 1, c = 0; c < LENGTH; c  ) {
        if (a < b) {
            arr[c] = '*';
            a  ;
        } else {
            arr[c] = ' ';
            a    = 0;
            b  ;
        }
    }

    printf(arr);
    return EXIT_SUCCESS;
}

Code result : * ** *** **** *****

CodePudding user response:

In the event that checking if a number is triangular by linking or writing some sort of sqrt() function is not a solution that you find acceptable:

Each group of **... in the final string has a ' ' at the end, so the shortest segment in the string is "* ", which is 2 chars long.

The c in your loop is the index of the char array that this iteration should write to, the a is the index inside the current group of '*'s, and b is length of the current group of '*'s less one (since we want to count the spaces). Directly before the if clause in your for loop, it can be said that c is the sum from 2 to b plus a.

In other words, if a=0, and b=1, then c=0, because the sum from 2 to 0 is 0, plus 0 is 0.

If a=3, and b=4, then c= (2 3 4) 3 = 12.

This means that you could write your code like this:

#include <stdio.h>

const int LENGTH = 20;

int sumFromTwo(int in){  //Recursive function to calculate sigma(2:in)
  if(in < 2)
    return 0;
  else
    return in   sumFromTwo(in - 1);
}

int main()
{
    char arr[LENGTH   1];  //Extra byte for null-terminator

    for (int a = 0, b = 1; sumFromTwo(b)   a < LENGTH ; ) {
        if (a < b) {
            arr[sumFromTwo(b)   a] = '*';
            a  ;
        } else {
            arr[sumFromTwo(b)   a] = ' ';
            a    = 0;
            b  ;
        }
    }

    arr[LENGTH] = '\0';  //Always null-terminate your strings

    printf(arr);
    return EXIT_SUCCESS;
}

But using recursion to avoid using a variable that is almost certainly going to be optimized into a register anyway is not going to save your computer any resources, least of all RAM, so it is definitely cleaner to do it the way you did in your question (but please null-terminate your string before passing it to your choice of printf or puts).

  • Related