CleverDev
CleverDev

Reputation: 487

Way to represent an object in C or dealing with multiple value return

I was wondering if you might be able to help, I'm trying to "convert" some code that was written in javascript to 'C' code, but I'm not sure how to deal with the object :

function updateObj(o, k) {
  return {
    n: o.n + 1,
    way: k + "-" + o.way
  }
}

function steps(k) {
  if (k == 1) {
    return {
      n: 2,
      way: "1-0<BR>"
    };
  }
  let case1 = updateObj(steps(k - 1),k);
  for (i = 2; k % i > 0; i++);
  if (k == i) {
    return case1;
  }
  let case2 = updateObj(steps(k / i),k);
  if (case1.n < case2.n) return case1
  else return case2;
}

document.write(steps(291).way);

How would you transfer it to 'C' ? Here is my try :

#include <stdio.h>
#include <conio.h>
#define MIN(x, y) (((x) < (y)) ? (x) : (y))


int steps(int num);

int main() {
    int res;
    res = steps(150);

    _getch();
    return 0;
}

int steps(k)
{

    int i = 0;
    if (k == 1) return 1;
    for (int i = 2; k%i > 0; i++);
    if (k == i) {
        return steps(k - 1);
    }
    return 1 + MIN(steps(k - 1), steps(k / i));
}

Upvotes: 0

Views: 64

Answers (2)

chux
chux

Reputation: 154065

Example of a close mapping of javascript to 'C' code.

// Include needed headers.
#include <stdio.h>
#include <stdlib.h>

// Form a struct
typedef struct {
  int n;
  char *way;  // Code will need to manage the strings - oh the joy of C!
} function;

function updateObj(function o, int k) {
  // Body left for OP to implement
  // Determine concatenation memory needs
  // Allocate
  // Concatenate
  // Free `o` resources
  // Form `function`
}

function steps(int k) {
  if (k == 1) {
    //     v---Compound Literal -----------------------v  Since C99
    return (function) {.n = 2, .way = strdup("1-0<BR>")};
  }
  function case1 = updateObj(steps(k - 1), k);
  int i;
  for (i = 2; k % i > 0; i++) {
    ;
  }
  if (k == i) {
    return case1;
  }
  function case2 = updateObj(steps(k / i), k);
  if (case1.n < case2.n) {
    function_free(case2);  // need to free resources in case2
    return case1;
  } else {
    function_free(case1);  // need to free resources in case1
    return case2;
  }
}

int main() {
  function f = steps(291);
  puts(f.way);
  function_free(f);
}

Upvotes: 1

piripiri
piripiri

Reputation: 2015

structs might be what you are looking for.

They can be used to group some kind of data. In order to declare a structure that contains an integer and a char pointer, use:

struct S {
  int i;
  char *c;
};

Then you can do something like:

struct S function() {
  struct S s;
  s.i = 1;
  // more code
  return s;
}

If your structure is memory intensive you might want to put it on the heap and return a pointer.

Upvotes: 1

Related Questions