CrazyEngineers
  • 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 ????
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • pooja sehgal

    MemberNov 2, 2008

    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??
    Are you sure? This action cannot be undone.
    Cancel
  • ankur8819

    MemberNov 2, 2008

    It is the total distance moved by all zero's or one's!
    Are you sure? This action cannot be undone.
    Cancel
  • pradeep_agrawal

    MemberNov 3, 2008

    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
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register