ankur8819
ankur8819
Branch Unspecified
04 Nov 2008

programming problem in C++

I was trying to solve this problem but got stuck.the problem goes like
I have a string of 0's and ones which is to be inputted by the user ..
may be something like "000110010"..The solution is a string in which I get 0's on one side and 1's on other side( like compaction where 0 represents used memory and 1 represents free memory)..+ the total distance (in terms of shifts) ..
For the string: 000110010..the output would be 000000111. and the diatance 1's or 0's have to be moved to achieve the output!
Can anyone help ????
pooja sehgal

pooja sehgal

Branch Unspecified
10 years ago
plz mention about d distance moved
we have to specify the distance moved by each 1 or 0 ????
or the total distance covrd by all 1's & 0's??
ankur8819

ankur8819

Branch Unspecified
10 years ago
It is the total distance moved by all zero's or one's!
pradeep_agrawal

pradeep_agrawal

Branch Unspecified
10 years ago
Below is a sample code for above problem statement.

#include "stdio.h"
#include "string.h"

#define MAX_STRING_LEN 100

int main() {
  char str[MAX_STRING_LEN + 1] = {0};
  int strl = 0;
  int move_count = 0;
  int move_pos = 0;
  int i = 0;

  scanf("%s", str);
  strl = strlen(str);  
  if(strl < 1) {
    printf("Empty string\n");
    return 0;
  }
  for(i = 0; i < strl; i++) {
    if((str[i] != '0') && (str[i] != '1')) {
      printf("Invalid character in string\n");
      return 0;
    }
  }

  for(i = strl -1, move_pos = strl - 1; i >= 0; i--) {
    if(str[i] == '1') {
      str[i] = '0';
      str[move_pos] = '1';
      move_count += move_pos - i;
      move_pos--;
    }
  }

  printf("Result string: %s\n", str);
  printf("Total movement: %d\n", move_count);

  return 0;
}
Compile the file with above code and run as:
a.exe < input.txt > output.txt [on windows]
a.out < input.txt > output.txt [on linux]

Here,
a.exe or a.out are the executables generated after compilation
input.txt is the file containing input string
output.txt is the output file containing result

-Pradeep

Share this content on your social channels -

Only logged in users can reply.