小言_互联网的博客

C#练习题答案: 最近的和最小【难度:3级】--景越C#经典编程题库,1000道C#基础练习题等你来挑战

415人阅读  评论(0)

最近的和最小【难度:3级】:

答案1:

using System;

public class ClosestWeight
{
    public static int[][] Closest(string strng)
    {
        if (strng.Length == 0)
            return new int[0][];

        string[] digits = strng.Split();
        int[] weights = new int[digits.Length];

        for (int i = 0; i < digits.Length; i++)
        {
            int w = 0;
            foreach (char c in digits[i])
            {
                w += c - '0';
            }
            weights[i] = w;
        }
        
        int closest = int.MaxValue;
        int closestIndexA = int.MaxValue;
        int closestIndexB = int.MaxValue;
        int smallestWeight = int.MaxValue;

        for (int i = 0; i < weights.Length; i++)
        {
            for (int j = i; j < weights.Length; j++)
            {
                if (j == i)
                    continue;
                    
                int w = Math.Abs(weights[i] - weights[j]);
                
                if (w > closest)
                    continue;
                    
                int combinedWeight = weights[i] + weights[j];
                
                if (w == closest)
                {
                    if (combinedWeight >= smallestWeight)
                        continue;
                }
                
                closest = w;
                smallestWeight = combinedWeight;
                
                if (weights[i] <= weights[j])
                {
                    closestIndexA = i;
                    closestIndexB = j;
                }
                else
                {
                    closestIndexA = j;
                    closestIndexB = i;
                }
            }
        }
        
        int[][] result = new int[2][];
        result[0] = new int[3] { weights[closestIndexA], closestIndexA, int.Parse(digits[closestIndexA]) };
        result[1] = new int[3] { weights[closestIndexB], closestIndexB, int.Parse(digits[closestIndexB]) };      
        return result;
    }
}

答案2:

using System;
using System.Collections.Generic;
using System.Linq;

public class ClosestWeight
{
    public static int[][] Closest(string str)
      => string.IsNullOrEmpty(str)
          ? new int[][] { }
          : str
              .Split(' ')
              .Select((x, i)
                  => new {Weight = SumOfDigits(x), Index = i, Original = int.Parse(x)})
              .OrderBy(x => x.Weight)
              .MinPairBy((a, b) => b.Weight - a.Weight)
              .Select(x => new[] {x.Weight, x.Index, x.Original})
              .ToArray();
              
    private static int SumOfDigits(string s)
      => s.Select(x => int.Parse(x.ToString())).Sum();
}

// Hide this ~
public static class LinqMinPairBy
{
    public static T[] MinPairBy<T>(this IEnumerable<T> source, Func<T, T, int> comparer)
        where T : class
    {
        using (var enumerator = source.GetEnumerator())
        {
            enumerator.MoveNext();
            var minPair = new [] {enumerator.Current, null};
            enumerator.MoveNext();
            minPair[1] = enumerator.Current;

            var previous = minPair[1];
            while (enumerator.MoveNext())
            {
                if (comparer(minPair[0], minPair[1]) > comparer(previous, enumerator.Current))
                {
                    minPair[0] = previous;
                    minPair[1] = enumerator.Current;
                }
                previous = enumerator.Current;
            }
            return minPair;
        }
    }
}

答案3:

using System;
using System.Linq;

public class ClosestWeight
{
    private static int cmp(int[] x, int[] y) 
    {
        int cp =  x[0] - y[0];
        if (cp == 0) 
            return x[1].CompareTo(y[1]);
        if (cp < 0) return -1; else return 1;
    }
    public static int[][] Closest(string strng) 
    {
        if (strng.Equals("")) return new int[][] {};
        string[] nums = strng.Split(' ');
        int[][] l = Enumerable.Range(0, nums.Length)
            .Select(v => new int[] { nums[v].Sum(x => (int)Char.GetNumericValue(x)), v, Convert.ToInt32(nums[v]) })
            .ToArray();
        Array.Sort(l, cmp);
        int[][] k = Enumerable.Range(1, l.Length-1).Select(u => new int[] { l[u][0] - l[u-1][0], u }).ToArray();
        Array.Sort(k, cmp);
        int ndx = k[0][1];
        int[][] result = new int[2][]{ l[ndx - 1], l[ndx] };
        return result;
    }
}

答案4:

using System;
using System.Linq;
using System.Collections.Generic;

public class ClosestWeight
{
    public static int[][] Closest(string strng) 
    {
        var nums = strng.Split(' ').Select((num, index) => new { OriginalValue = num, Weight = num.Sum(c => c - '0'), Index = index }).OrderBy(w => w.Weight).ToArray();
        var minDiff = Enumerable.Range(0, nums.Length - 1).Select(i => new { A = nums[i], B = nums[i + 1], Diff = nums[i + 1].Weight - nums[i].Weight }).OrderBy(diff => diff.Diff).First();
        return new int[][] {
            new int[] { minDiff.A.Weight, minDiff.A.Index, int.Parse(minDiff.A.OriginalValue) },
            new int[] { minDiff.B.Weight, minDiff.B.Index, int.Parse(minDiff.B.OriginalValue) }
        };
    }
}

答案5:

using System;
using System.Linq;

public class ClosestWeight
{
  public static int[][] Closest(string s) 
  {
    var w = s.Split().Select((x,i) => new []{ x.Sum(c => c - '0'), i, Int32.Parse(x) }).OrderBy(x => x[0]);
    return s.Length == 0 ? new int[0][] :
           w.Zip(w.Skip(1), (a, b) => new { D = b[0] - a[0], V = new []{a, b} }).OrderBy(x => x.D).First().V;
  }
}

答案6:

using System;
using System.Collections.Generic;
using System.Linq;

public class ClosestWeight
{
    public static int sumDigits(string s){
      int sum = 0;
      foreach (char num in s){sum += int.Parse(num.ToString());}
      return sum;
    }
    public static int[][] Closest(string s) 
    {
        string[] nums = s.Split(new char[0]);
        int[][] output = new int[nums.Length][];
        for (int i = 0; i < nums.Length; i++){
        output[i] = new int[]{ClosestWeight.sumDigits(nums[i]),i,int.Parse(nums[i])};}
        var sorted = (from tuple in output
                      orderby tuple[0] ascending, tuple[1] ascending
                      select tuple).ToArray();
                      
        int[] min = new int[2]{1000000,0};
        for(int x =1; x < sorted.Length;x++){
        if(sorted[x][0]-sorted[x-1][0] < min[0]){min = new int[2]{sorted[x][0]-sorted[x-1][0],x-1};}}
        return new int[2][]{sorted[min[1]],sorted[min[1]+1]};
    }
}

答案7:

using System;
using System.Linq;
public class ClosestWeight
{
        public static int[][] Closest(string strng)
        {
            if (string.IsNullOrEmpty(strng)) return new int[0][];
            var arr = strng.Split(' ').Select((x, i) => new[] {x.Sum(y => y - '0'), i, int.Parse(x)}).OrderBy(x => x[0]).ThenBy(x => x[1]).ToArray();
            var min = arr[1][0] - arr[0][0];
            var left = arr[0];
            var right = arr[1];
            for (int i = 2; i < arr.Length; i++)
            {
                if (arr[i][0] - arr[i-1][0] < min)
                {
                    min = arr[i][0] - arr[i - 1][0];
                    left = arr[i - 1];
                    right = arr[i];
                }
            }
            return new[] {left, right};
        }
}

答案8:

using System;
using NUnit.Framework;
using System.Linq;

    public class ClosestWeight
    {
        public static int[][] Closest(string strng)
        {
            if (String.IsNullOrEmpty(strng))
                return new int[][] { };
            var sorted = strng.Split(' ').Select((x, index) => new int[] { x.Select(n => (int)char.GetNumericValue(n)).Sum(), index, Int32.Parse(x) }).OrderBy(x => x[0]).ToArray();
            int min = sorted[1][0] - sorted[0][0];
            int i1 = 0, i2 = 1;
            for (int i = 1; i < sorted.Length - 1; i++)
            {
                if((sorted[i + 1][0] - sorted[i][0]) < min)
                {
                    i1 = i;
                    i2 = i + 1;
                    min = sorted[i + 1][0] - sorted[i][0];
                }
            }
            return new int[][] { sorted[i1], sorted[i2] };
        }
    }

答案9:

using System;
using System.Collections.Generic;
public class ClosestWeight
{
   public static int[][] Closest(string strng)
        {
            if (strng != "")
            {
                string[] numbers = strng.Split(' ');
                List<int> weights = new List<int>();
                foreach (string i in numbers)
                {
                    weights.Add(GetWeight(i));
                }
                int min = Math.Abs(weights[0] - weights[1]);
                int F_index = 0;
                int S_index = 1;
                int sum = weights[0] + weights[1];
                for (int i = 0; i < weights.Count -1; i++)
                {
                    for (int j = i + 1; j < weights.Count; j++)
                    {
                        int newMin = Math.Abs(weights[i] - weights[j]);
                        int newSum = weights[i] + weights[j];
                        if (min > newMin || (min == newMin &amp;&amp; newSum < sum))
                        {
                            min = newMin;
                            F_index = i;
                            S_index = j;
                            sum = newSum;
                        }
                    }
                }
                if (weights[F_index] <= weights[S_index])
                {
                    return new int[2][] { new int[] { weights[F_index], F_index, int.Parse(numbers[F_index]) }, new int[] { weights[S_index], S_index, int.Parse(numbers[S_index]) } };
                }
                else
                {
                    return new int[2][] { new int[] { weights[S_index], S_index, int.Parse(numbers[S_index]) }, new int[] { weights[F_index], F_index, int.Parse(numbers[F_index]) } };
                }
            }
            else
            {
                return null;
            }
        }
        public static int GetWeight(string str)
        {
            int result = 0;
            foreach (char i in str)
            {
                result += i - 48;
            }
            return result;
        }
}

答案10:

using System;
using System.Linq;
using System.Collections.Generic;

public class ClosestWeight
{
    public static int[][] Closest(string inputString) 
    {
        if (inputString.Length < 1) return new int[0][];
        var sorted = (from o in Option.GetOptions(inputString.Split(' ')) orderby o.OriginalString.NumericalValue() select o).ToList();
            var comparison = AllComparisons(sorted);
            var lowest = (from c in comparison orderby c.Difference ascending select c).First();
            List<int[]> arrayList = new List<int[]>();
            if(lowest != null)
            {
                int[] first = lowest.Options[0].ToIntArray();
                int[] second = lowest.Options[1].ToIntArray();
                int[][] retVal = new int[2][] { new int[]{ first[0], first[1], first[2] }, new int[]{ second[0], second[1], second[2] } };
                return retVal;
            }


            return null;
        }

        static List<Comparison> AllComparisons(List<Option> options)
        {
            List<Comparison> retVal = new List<Comparison>();
            for (int x=0; x< options.Count - 1; x++)
            {
                for(int i=(x+1); i<options.Count; i++)
                {
                    retVal.Add(new Comparison(options[x], options[i]));
                }
            }
            return retVal;
        }


        class Option
        {
            public string OriginalString { get; set; }
            public int OriginalIndex { get; set; }
            public int WeightedValue { get { return OriginalString.NumericalValue(); } }

            public Option(string s, int i)
            {
                OriginalString = s;
                OriginalIndex = i;
            }

            public static List<Option> GetOptions(string[] stringOptions)
            {
                List<Option> retVal = new List<Option>();
                int counter = 0;
                foreach (string s in stringOptions)
                {
                    retVal.Add(new Option(s, counter));
                    counter++;
                }
                return retVal;
            }

            public int[] ToIntArray()
            {
                return new int[3] { WeightedValue, OriginalIndex, Convert.ToInt32(OriginalString) };
            }
        }

        class Comparison
        {
            public Option[] Options { get; set; }
            public int Difference { get { return Math.Abs(Options[0].WeightedValue - Options[1].WeightedValue); } }

            public Comparison(Option a, Option b)
            {
                Options = new Option[2] { a, b };
            }
        }

        
    }

    public static class StringExtension
    {
        public static int NumericalValue(this string input)
        {
            int retVal = 0;
            foreach (char c in input)
            {
                retVal += Convert.ToInt32(c.ToString());
            }
            return retVal;
        }
    }




转载:https://blog.csdn.net/weixin_45444821/article/details/101830296
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场