如何创建升序的数组,然后下降的数字? [英] How do I create an array of ascending and then descending numbers?

查看:167
本文介绍了如何创建升序的数组,然后下降的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

我有最小和最大值和数目的增量可以是奇数或偶数;

如果我分= 3和max = 10,增量= 15,然后我想:

  3,4,5,6,7,8,9,10,9,8,7,6,5,4,3

不过,如果增量= 16我想(注意中间两个10片):

  3,4,5,6,7,8,9,10,10,9,8,7,6,5,4,3

我要创建这些阵列附加特殊使用只是最小值,最大值和增量数。

更新:

要使其更清楚增量数等于物品必须是阵列中的数量和项目是小数。

所以,如果分= 5.0和max = 15.0和增量= 6则数组将包含:

  5.0,10.0,15.0,15.0,10.0,5.0


解决方案

这应该工作:

 公共静态的IEnumerable<&小数GT; NewMethod(十进制分钟,十进制最大,诠释计数)
{
    变种增量=(最大 - 最小)/(INT)((计数 - 1)/ 2);    对于(VAR I =分钟; I<最大; I + =增量)
        产生回报我;    如果(计数%2 == 0)
        产生最大的回报;    对于(VAR I = MAX; I> =分钟; I - =增量)
        产生回报我;
}

样品测试:

  VAR分钟=3.0米;
VAR最大=10.0米;
变种数= 16;MessageBox.Show(的string.join(,,NewMethod(最小值,最大值,计数)));

编辑:您必须应对浮点类型损失precision,否则你将丢失在最终的结果集的元素。修补一点与 Math.Round I + = I - = 部分,这是给你的。我已经更新code来代替双击更可靠的小数键入。但也不能保证这不应该失败,每一次。更简单的是为了避免情况下,您将需要小数类型,如结果 {1,2.2,3.4} 等。

For example:

I have min and max values and a number of increments which may be odd or even;

if I have min = 3 and max = 10 and increments = 15 then I want:

3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3

However, if increments = 16 I want (notice the two 10's in the middle):

3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3

I have to create these arrays add-hoc using just min, max, and number of increments.

UPDATE:

To make this clearer the number of increments is equal to the number of items that must be in the array and the items are decimals.

so if min = 5.0 and max = 15.0 and increments = 6 then the array would contain:

5.0, 10.0, 15.0, 15.0, 10.0, 5.0

解决方案

This should work:

public static IEnumerable<decimal> NewMethod(decimal min, decimal max, int count)
{
    var increment = (max - min) / (int)((count - 1) / 2);

    for (var i = min; i < max; i += increment)
        yield return i;

    if (count % 2 == 0)
        yield return max;

    for (var i = max; i >= min ; i -= increment)
        yield return i;
}

Sample test:

var min = 3.0m;
var max = 10.0m;
var count = 16;

MessageBox.Show(string.Join(", ", NewMethod(min, max, count)));

Edit: You have to cope with floating point types losing precision, otherwise you will be missing an element in the final result set. Tinker a bit with Math.Round over the i += and i -= part, that's up to you. I have updated code to replace double with more reliable decimal type. But there is no guarantee this should not fail every time. Easier is to avoid cases where you will need decimal types in the result like { 1, 2.2, 3.4 } etc.

这篇关于如何创建升序的数组,然后下降的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆