Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Общие вопросы по .NET и C# > Разбивка/Распределение суммы по элементам массива


Автор: Олег13 16.10.2015, 11:34
Всем добрый день!
В общем вопрос такой: необходимо вводимую сумму разбить по элементам массива. Например: есть массив из 6 элементов типа int, каждый массив должен содержать сумму не более 2000, т. е. например вводим сумму 7000 и она разбивается так: 1-й элемент=2000, 2-й элемент=2000, 3-й элемент=2000, 4-й элемент=1000. Я состряпал вариант решения данного вопроса (см. ниже), но по моему как-то коряво получилось, может у кого-нибудь есть более элегантный способ решения?

Код

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication5
{
    public partial class Form1 : Form
    {
        int[] myArr = new int[6];

        public Form1()
        {
            InitializeComponent();
          
        }

        private void button1_Click(object sender, EventArgs e)
        {           

            int s = 2000;
            for (int i = 0; i <= myArr.Length-1; i++)
            {
                if (myArr[i] == 0)
                {
                    double res = Convert.ToInt16(textBox1.Text) / s;

                    for (int r = i; r <= res-1; r++)
                    {
                        myArr[r] = s;
                    }
                }
            }

            for (int i1 = 0; i1 <= myArr.Length - 1; i1++)
            {
                if (myArr[i1] == 0)
                {
                    double res1 = Convert.ToInt16(textBox1.Text) % s;
                                     
                    myArr[i1] = Convert.ToInt16(res1);
                    break;                    
                }
            }
            
            //Вывод результатов            
            for (int a = 0; a <= myArr.Length-1; a++)
            {
                listBox1.Items.Add(myArr[a]);
            }              
            
        }        
    }
}
  

Автор: Олег13 19.10.2015, 12:10
Похоже мыслей ни у кого нет

Автор: Angel_666 20.10.2015, 11:04
Мне кажется что так по компактней будет:
using System;

namespace DistributionArray
{
    class Program
    {    
        public static void Main(string[] args)
        {            
            int[] myArr = new int[6];
            int s = 2000;
            int summ = 0;
            
            Console.Write("Введите сумму!");
            summ = Convert.ToInt16(Console.ReadLine());
            
            int whole = summ / s;
            for (int i = 0; i < whole; i++)
            {
                myArr[i] = s;
            }
            
            myArr[whole] = summ % s;
                     
            for (int a = 0; a < myArr.Length; a++)
            {
             Console.Write("{0:D}\r\n", myArr[a].ToString());
            }
            
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}

Этот ответ добавлен с нового Винграда - http://ru.vingrad.com/Razbivka-Raspredeleniye-summy-po-elementam-massiva-id5620b6f2ae20152b5b8b4567#findElement_E7045_5625f581ae2015ed140472e4_0

Автор: Олег13 21.10.2015, 03:37
Спасибо, тоже неплохой вариант.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)