perl:为数组中的每个元素找到最接近的较小数字

时间:2016-09-04 06:02:39

标签: arrays perl

想要为数组中的每个元素生成最接近较小数字的数组。(如果元素为0,则为-1)

示例

输入数组:8 2 4 5 1 6 0 3 2

输出数组:2 1 2 1 0 0 -1 0 0

2 个答案:

答案 0 :(得分:0)

蛮力方法在这里看起来并不是一个坏主意。

use strict;
use warnings;

use List::Util 'min';

my @in = qw/8 2 4 5 1 6 0 3 2/;

my @out;

for my $index (0..$#in) {
    for my $offset (1..$#in) {
        my $least = min(
            $index-$offset >= 0 ? $in[$index-$offset] : (),
            $index+$offset <= $#in ? $in[$index+$offset] : ()
        );

        if ( ! defined $least ) {
            push @out, -1;
            last;
        }
        elsif ( $least < $in[$index]) {
            push @out, $least;
            last;
        }
    }
}

print "@out\n";

答案 1 :(得分:0)

C#代码以获取数组中最接近的较小元素

        Console.WriteLine("How many numbers you want in your array? ");
        int length = Convert.ToInt32(Console.ReadLine());
        int[] myArray = new int[length];
        int[] resultArray = new int[length];

        Console.WriteLine("Enter " + length + " numbers for your array..");
        for (int i = 0; i < myArray.Length ; i++)
        {
            myArray[i] = Convert.ToInt32(Console.ReadLine());
        }

        for (int i = 0; i < myArray.Length; i++) {
            int k = -1;
            for (int j = 0; j < myArray.Length; j++) {
                if (myArray[i] > myArray[j] && (k == -1 || ((i - Array.IndexOf<int>(myArray, k) >= Math.Abs(i - j) ) && k > myArray[j] )))
                {
                    k = myArray[j];
                }
            }
            resultArray[i] = k;
        }

        Console.WriteLine("Desired Output: ");
        for (int i = 0; i < resultArray.Length; i++)
        {
            Console.WriteLine(resultArray[i]);
        }

        Console.ReadLine();