2

I need to find the degree of inversion for a set of numbers in a file.

I read input from a .txt file in the form:

SET 1: -3 1 2 0 4
SET 2: 0 1 2 3 4 5
SET 4: 29 39 0 1 3

I do not know how to separate the input (the set and its numbers). I thought of putting them in a struct but so far it's not working. The degree of inversion = number of numbers that are smaller than their index value. For example, in SET 2, the degree of inversion is 0.

Bilal Siddiqui
  • 349
  • 3
  • 17
Simm
  • 89
  • 1
  • 10
  • 4
    Welcome to SO. The idea for a question like this is that you post the code you have so far and describe the problem you have with that code. Then someone might tell what's wrong and how to correct it or someone might suggest a better approach. – Support Ukraine Aug 14 '18 at 10:24
  • "so far it's not working" --> post that non-working code. – chux - Reinstate Monica Aug 14 '18 at 13:57
  • If you do not need them later do not store them, iterate over the input immediately. What is your issue? – Johannes Aug 14 '18 at 15:20

1 Answers1

0

You need to post code on where you are stuck; that is the best way to get help. Anyway, here is some rough code to help you identify where your issues may be. I have kept it simple to allow you to follow through with how vanilla C does I/O.

#include <stdio.h>                   /* snprinf, fprintf fgets, fopen, sscanf */

int main(void)
{
  char line_buffer[64];
  FILE* infile = fopen("yourfile.txt", "r");         /* open file for reading */
  while(fgets(line_buffer, 64, infile) != NULL)
  {
    char set_name[8];                 /* construct a string w/ the set number */
    snprintf(set_name, 8, "SET %c:", *(line_buffer+4));    /* no. is 5th char */
    fprintf(stdout, "%s ", set_name);           /* fprintf w/ stdout = printf */

    int set[8];
    int ind = 0;
    for(int i=7; line_buffer[i]!='\0';)    /* start from first number and end */
    {                       /* when string ends, denoted by the '\0' sentinel */
      int n;    /* using pointer arithmetric, read in and store num & consume */
      sscanf(line_buffer+i, "%d %n", set+ind, &n);     /* adjacent whitespace */
      i += n;               /* n from sscanf tells how many chars are read in */
      fprintf(stdout, "%d ", set[ind]);
      ind +=1;
    }

    fprintf(stdout, "\n");
  }

  return 0;
}
Bilal Siddiqui
  • 349
  • 3
  • 17