Last ant on rod in C

Last ant on rod


Level: Difficult

There are 'n' ants on a 'n+1' length rod. The ants are numbered from 1 to n and are initially placed at positions starting from position 1 till position n. They are moving either in left direction (denoted by '-1') or in the right direction (denoted by '1'). Whenever an ant crosses the boundary of the rod it falls off the rod. You are given the initial direction of the ants. Now, whenever two ants collide their direction switches, i.e. the ant going in left direction ('-1) changes it's direction towards right ('1') and the ant going in the right direction ('1') changes it's direction towards left ('-1'). Find last ant to fall off the rod.
Note: In case two ants are falling simultaneously in the end print the index of the lower indexed ant.

Input Format:
First line contains the integer 'n' denoting the total number of ants s.t. 1 <= n <= 1,000
Second line contains 'n' space separated numbers (either '1' or '-1') denoting the initial directions of the ants.

Output Format:
Output a single integer which is the index (lower index in case two ants are falling simultaneously in the end) of the last ant to fall off the table.


Input                
Output
Test Case 1
2          
 1 1
1
Test Case 2
3          
1 -1 -1
2
Test Case 3
2          
  -1 -1
2
Test Case 4
8   
 1 1 -1 1 1 1 -1 1
3
Test Case 5
10     1 -1 1 1 -1 1 -1 1 -1 -1
5
#include <stdio.h>

int main(){
 // Number of ants
 int n;
 scanf("%d", &n);
 int a[n];
 int i;
 // Directions of ants
 for(i=0; i<n; i++){
  scanf("%d", &a[i]);
 }
 int left = 0, right = 0;
 // Number of contiguous ants at left edge and moving towards left
 for(i=0; i<n; i++){
  if(a[i] == -1){
   left ++;
  }
  else{
   break;
  }
 }
 // Number of contiguous ants at the right edge and moving towards right
 for(i=n-1; i>=0; i--){
  if(a[i] == 1){
   right++;
  }
  else{
   break;
  }
 }
 
 // Number of ants between 'left' and 'right' position and moving towards left
 int leftgoingants = 0;
 for(i=left; i <= n-right-1; i++){
  if(a[i] == -1){
   leftgoingants ++;
  }
 }
 if(left >= right){
  printf("%d", left + leftgoingants);
 }
 else{
  printf("%d", left + leftgoingants + 1);
 }
 return 0;
}


// Check the following link for a detailed explanation. 
// https://drive.google.com/a/nptel.iitm.ac.in/#folders/0BwzHeT8eBmvCUUlwNWo1VzM0Xzg

Labels: ,