Sunday, April 7, 2013

SRM 575 - Division II, Level One

Problem Statement :-

                  John has a sequence of integers. Brus is going to choose two different positions in John's sequence and swap the elements at those positions. (The two swapped elements may have the same value.) Return the number of different sequences Brus can obtain after he makes the swap.

Examples

0)
    
{4, 7, 4}
Returns: 3
If Brus swaps elements 0 and 1 (0-based indices), the sequence will change to {7, 4, 4}. If he swaps elements 1 and 2 instead, the sequence will change to {4, 4, 7}. Finally, if the swaps elements 0 and 2, the sequence will remain {4, 7, 4}. These three outcomes are all distinct.
1)
    
{1, 47}
Returns: 1
Brus has to swap the only two elements, producing the sequence {47, 1}. Note that Brus has to make the swap, he cannot keep the original sequence.
2)
    
{9, 9, 9, 9}
Returns: 1
Regardless of which two elements Brus swaps, the resulting sequence will always be {9, 9, 9, 9}.
3)
    
{22, 16, 36, 35, 14, 9, 33, 6, 28, 12, 18, 14, 47, 46, 29, 22, 14, 17, 4, 15, 28, 6, 39, 24, 47, 37}
Returns: 319

My Solution :-

using System;
using System.Collections.Generic;
public class TheSwapsDivTwo {
  public int find(int[] sequence) {
        int c = 0;
        bool hasDup = false;
        for (int idx = 0; idx < sequence.Length; idx++)
        {
            for (int j = idx + 1; j < sequence.Length; j++)
            {
                if (sequence[idx] != sequence[j])
                {
                    c++;
                }
                else
                {
                    hasDup = true;
                }
            }
        }

        return c + ((hasDup)?1:0);
  }
}
 


 

No comments:

Post a Comment