码迷,mamicode.com
首页 > 其他好文 > 详细

Where is Vasya?

时间:2015-07-05 07:06:36      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:

Where is Vasya?

Vasya stands in line with number of people p (including Vasya), but he doesn‘t know exactly which position he occupies. He can say that there are no less than b people standing in front of him and no more than apeople standing behind him. Find the number of different positions Vasya can occupy.

Input

As an input you have 3 numbers:

1. Total amount of people in the line;

2. Number of people standing in front of him

3. Number of people standing behind him

Examples

Line.WhereIsHe(3, 1, 1) // => 2 The possible positions are: 2 and 3
Line.WhereIsHe(5, 2, 3) // => 3 The possible positions are: 3, 4 and 5

The third parameter is not irrelavant and is the reason why (9,4,3) is 4 not 5
you have to satisfy both conditions
no less than bef people in front of him
and
no more than aft people behind him

as far as i can tell all the test cases are correct

9个人,前面的人不少于4个,后面的人不多于3个的话,可以占据6,7,8,9 是个位置

第五个位置,虽然前面是4个人,但是后面也是4个人。后面的人数超过3了,就不符合。

using System;

public class Line
    {
        public static int WhereIsHe(int p, int bef ,int aft)
        { 
           // Your code is here...
           int count=0;
           int a=0;//people infront of him
           int b=0;//people behind him
          for(int i=1;i<=p;i++)
          {
           a=i-1;
           b=p-i;
           if(a>=bef&&b<=aft)
           {
           count++;
           }
          }
          return count;
        }
    }

 使用Linq进行简化后:

using System;
using System.Linq;
public static int WhereIsHe(int p, int bef, int aft)
{
    return Enumerable.Range(1, p).Where(x => x - 1 >= bef && p - x <= aft).Count();
}

 

 

其他人的解法

using System;

public class Line
    {
        public static int WhereIsHe(int p, int bef ,int aft)
        { 
           return Math.Min(p-bef,aft+1);
        }
    }

 

Where is Vasya?

标签:

原文地址:http://www.cnblogs.com/chucklu/p/4621581.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!