0

I have faced with a programming challenge, which I had to calculate the sum of every array which is in my nested array. In this problem the input is given by the user, and we must start from the must inner array, and then sum it with result of outer arrays.

Sample 1:

{1, 2, {3, {4, 5, {6}}, 7}, 8}

Output 1:

6
15
25
36

Sample 2:

{{12, 23, {4, 0, {1}, {1}}}, 0, {1}}

Output 2:

1
1
6
41
1
42

Sample 3:

{1, {2, {{6}}}, {{{7}}}}

Output 3:

6
6
8
7
7
7
16

My idea was to use the Dynamic Prpgramming strategy for solving this problem, but I am not sure about it, and since the limitations in C are a bit more than the other programming languages, everything gets a bit harder.

Edit

I find a similarity between this question, and implementing a calculator using a Stack data structure.

So I decided to implement a stack of strings, and then add all the { and } characters and also numbers to it. I would ignore the spaces and ,. But when reaching a }, we should calculate the sum.

Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
/*
    https://www.techiedelight.com/stack-implementation/
    https://stackoverflow.com/a/1922239/20285050
    https://stackoverflow.com/a/1726321/20285050
    https://stackoverflow.com/a/8257754/20285050 for converting int to string
    https://www.educative.io/answers/how-to-convert-a-string-to-an-integer-in-c
    https://stackoverflow.com/a/5099675/20285050
*/


struct stack_entry
{
    char *data;
    struct stack_entry *next;
};


struct stack_t
{
    struct stack_entry *head;
    size_t stackSize;
};


struct stack_t *newStack(void)
{
    struct stack_t *stack = (struct stack_t*)malloc(sizeof *stack);
    if (stack)
    {
        stack->head = NULL;
        stack->stackSize = 0;
    }
    return stack;
}


char *copyString(char *str)
{
    char *tmp = (char*)malloc(strlen(str) + 1);
    if (tmp)
        strcpy(tmp, str);
    return tmp;
}


void push(struct stack_t *theStack, char *value)
{
    struct stack_entry *entry = (struct stack_entry*)malloc(sizeof *entry);
    if (entry)
    {
        entry->data = copyString(value);
        entry->next = theStack->head;
        theStack->head = entry;
        theStack->stackSize++;
    }
    else
    {
    }
}

int isEmpty(struct stack_t *theStack)
{
    if (theStack -> stackSize == 0)
    {
        return 1;
    }
    return 0;
}

char *top(struct stack_t *theStack)
{
    if (theStack && theStack->head)
        return theStack->head->data;
    else
        return NULL;
}


void pop(struct stack_t *theStack)
{
    if (theStack->head != NULL)
    {
        struct stack_entry *tmp = theStack->head;
        theStack->head = theStack->head->next;
        free(tmp->data);
        free(tmp);
        theStack->stackSize--;
    }
}


void clear(struct stack_t *theStack)
{
    while (theStack->head != NULL)
        pop(theStack);
}


void destroyStack(struct stack_t **theStack)
{
    clear(*theStack);
    free(*theStack);
    *theStack = NULL;
}

void evaluate(char expression[], int values[])
{
    struct stack_t *operations = newStack();
    for (int i = 0; i < 1000; i++)
    {
        char *expChar;
        if (expression[i] == ' ' || expression[i] == ',')
        {
            continue;
        }
        else if (expression[i] == '{')
        {
            expChar = &expression[i];
            push(operations, expChar);
        }
        else if (isdigit(expression[i]))
        {
            char svalue[5];
            int value = 0;
            while (i < 1000 && isdigit(expression[i]))
            {
                value = (value * 10) + (expression[i] - '0');
                i++;
            }
            itoa(value, svalue, 10);
            push(operations, svalue);
            i--;
        }
        else if (expression[i] == '}')
        {
            char sans[5];
            int ans = 0;
            char openBrace = '{';
            expChar = &openBrace;
            while (!isEmpty(operations) && top(operations) != expChar)
            {
                char svalue[5];
                strcpy(svalue, top(operations));
                pop(operations);
                int value = atoi(svalue);
                ans += value;
                values[i] = ans;
                // char op[1];
                // strcpy(op, top(operations));
                // pop(operations);
            }
            itoa(ans, sans, 10);
            push(operations, sans);
        }
        else {

        }
    }
}



int main()
{
    printf(" ******  please enter an expression for 
    evaluating******\n");
    char data[1000];
    fgets(data, 1000, stdin);

    int values[1000] = {0};
    evaluate(data, values);
}

I will be grateful for any help and advice.

  • 3
    what have you tried so far? This isn't a programming service nor is it a challenge solving service, but if you try something and bring the code here, we'll help you get it working – erik258 Oct 22 '22 at 15:11
  • If you can use libraries and user input looks like you've posted - just call some python or lua library and bingo. Life is short and suffering is not mandatory. Interfacing C with python/lua is a practical skill for which I'd give learning credits. – ddbug Oct 22 '22 at 15:22
  • Just make recursive function, and if there are no sub-arrays sum it up and print/return the result to the parent function. – Sven Nilsson Oct 22 '22 at 15:58
  • I know it is too late, but I have added the code which I am working on it. May you please take a look at it? Thanks.@erik258 – Aylin Naebzadeh Oct 28 '22 at 13:48
  • You have two questions here. 1) You are encountering a very specific [_segmentation fault_](https://stackoverflow.com/questions/2346806/what-is-a-segmentation-fault) error which could be [debugged](https://stackoverflow.com/questions/3718998/fixing-segmentation-faults-in-c) and isolated. or 2) Your intuition about using a stack is right-- you could ask for other ways of solving the problem, but it's too unfocused a question unless there's something specific about your stack approach that is unsatisfactory to you. – Wyck Oct 28 '22 at 14:28
  • Yes, you are right. I have changed my code a bit, and now I don't get `Segmentation fault`. I am debugging my code simultaneously, to check for the final result which will be returned by my function.@Wyck – Aylin Naebzadeh Oct 28 '22 at 14:34
  • Don't read past the NUL terminating character of your input string. `for (int i = 0; i < 1000; i++)` and `while (i < 1000 && isdigit(expression[i]))` *slap on the wrist*. That's not a good way to process your string data. – Wyck Oct 28 '22 at 14:44
  • I know it is not a good way, but I was forced to add a big number for iteration, for example, `1000`, because when I want to upload my code on a server `\n` or `\0` are not known.@Wyck – Aylin Naebzadeh Oct 28 '22 at 14:49

0 Answers0