将算法应用于多个文件

时间:2017-04-19 18:10:09

标签: c# algorithm file sorting

我目前正在开展一个项目,我必须选择一个文件,然后将其与其他文件一起排序。文件只是填充数字,但每个文件都有链接数据。因此,文件中的第一个数字链接到第二个文件中的第一个数字,依此类推。我目前有代码允许我读取文件并显示未排序的文件并使用冒泡排序进行排序。我不确定如何能够同时将同样的原则应用于多个文件。这样我就可以选择一个文件,然后按照我对单个文件所用的相同方法对其进行排序。

目前,程序加载并要求用户在1和2之间进行选择.1显示未排序的代码,2显示已排序的代码。我可以读取文件,但问题是按顺序排序和显示。基本上我如何排序链接在一起的多个文件。我需要采取哪些步骤才能做到这一点?

一个文件的示例:

4    
28    
77    
96

第二个文件的示例:

66.698    
74.58    
2.54    
48.657 

任何帮助将不胜感激。 感谢

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

public class Program

{
public Program()
{ 
}

public void ReadFile(int [] numbers)
{
    string path = "Data1/Day_1.txt";
    StreamReader sr = new StreamReader(path);


    for (int index = 0; index < numbers.Length; index++)
    {
        numbers[index] = Convert.ToInt32(sr.ReadLine());
    }

    sr.Close(); // closes file when done
}

public void SortArray(int[] numbers)
{
    bool swap;
    int temp;

    do
    {
        swap = false;
        for (int index = 0; index < (numbers.Length - 1); index++)
        {
            if (numbers[index] > numbers[index + 1])
            {
                temp = numbers[index];
                numbers[index] = numbers[index + 1];
                numbers[index + 1] = temp;
                swap = true;
            }
        }
    } while (swap == true);
 }

public void DisplayArray(int[] numbers)
{
    for(int index = 0; index < numbers.Length; index++)
    {
        Console.WriteLine("{0}", numbers[index]);
    }
  }
}

主要是在另一个文件中,以保持工作井井有条:

使用System;

public class FileDemoTest
{
public static void Main(string[] args)
{
    int[] numbers = new int[300];
    Program obj = new Program();
    int operation = 0;


    Console.WriteLine("1 or 2 ?");
    operation = Convert.ToInt32(Console.ReadLine());

    // call the read from file method
    obj.ReadFile(numbers);

    if (operation == 1)
    {
        //Display unsorted values
        Console.Write("Unsorted:");
        obj.DisplayArray(numbers);
    }

    if (operation == 2)
    {
        //sort numbers and display
        obj.SortArray(numbers);
        Console.Write("Sorted: ");
        obj.DisplayArray(numbers);
    }

 }
}

1 个答案:

答案 0 :(得分:1)

我要做的是创建一个类,它将保存文件1和文件2中的值。然后,您可以通过读取这两个文件中的值来填充这些类的列表。之后,您可以对任一字段中的类列表进行排序,并保持关系(因为这两个值存储在单个对象中)。

以下是保存文件数据的类的示例:

public class FileData
{
    public int File1Value { get; set; }
    public decimal File2Value { get; set; }

    /// <summary>
    /// Provides a friendly string representation of this object
    /// </summary>
    /// <returns>A string showing the File1 and File2 values</returns>
    public override string ToString()
    {
        return $"{File1Value}: {File2Value}";
    }
}

然后,您可以创建一个读取这两个文件的方法,并创建并返回这些对象的列表:

public static FileData[] GetFileData(string firstFilePath, string secondFilePath)
{
    // These guys hold the strongly typed version of the string values in the files
    int intHolder = 0;
    decimal decHolder = 0;

    // Get a list of ints from the first file
    var fileOneValues = File
        .ReadAllLines(firstFilePath)
        .Where(line => int.TryParse(line, out intHolder))
        .Select(v => intHolder)
        .ToArray();

    // Get a list of decimals from the second file
    var fileTwoValues = File
        .ReadAllLines(secondFilePath)
        .Where(line => decimal.TryParse(line, out decHolder))
        .Select(v => decHolder)
        .ToArray();

    // I guess the file lengths should match, but in case they don't, 
    // use the size of the smaller one so we have matches for all items
    var numItems = Math.Min(fileOneValues.Count(), fileTwoValues.Count());

    // Populate an array of new FileData objects
    var fileData = new FileData[numItems];
    for (var index = 0; index < numItems; index++)
    {
        fileData[index] = new FileData
        {
            File1Value = fileOneValues[index],
            File2Value = fileTwoValues[index]
        };
    }

    return fileData;
}

现在,我们需要修改您的排序方法以处理FileData数组而不是int数组。我还添加了一个参数,如果设置为false,将对File2Data字段而不是File1Data进行排序:

public static void SortArray(FileData[] fileData, bool sortOnFile1Data = true)
{
    bool swap;

    do
    {
        swap = false;
        for (int index = 0; index < (fileData.Length - 1); index++)
        {
            bool comparison = sortOnFile1Data
                ? fileData[index].File1Value > fileData[index + 1].File1Value
                : fileData[index].File2Value > fileData[index + 1].File2Value;

            if (comparison)
            {
                var temp = fileData[index];
                fileData[index] = fileData[index + 1];
                fileData[index + 1] = temp;
                swap = true;
            }
        }
    } while (swap);
}

最后,您可以显示未排序和排序的数据列表。注意我向用户添加了第二个问题,如果他们选择“排序”,他们可以决定是否应该按File1或File2排序:

private static void Main()
{
    Console.WriteLine("1 or 2 ?");
    int operation = Convert.ToInt32(Console.ReadLine());

    var fileData = GetFileData(@"f:\public\temp\temp1.txt", @"f:\public\temp\temp2.txt");

    if (operation == 1)
    {
        //Display unsorted values
        Console.WriteLine("Unsorted:");
        foreach (var data in fileData)
        {
            Console.WriteLine(data);
        }
    }

    if (operation == 2)
    {
        Console.WriteLine("Sort on File1 or File2 (1 or 2)?");
        operation = Convert.ToInt32(Console.ReadLine());

        //sort numbers and display
        SortArray(fileData, operation == 1);
        Console.WriteLine("Sorted: ");
        foreach (var data in fileData)
        {
            Console.WriteLine(data);
        }
    }

    Console.Write("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

如果您想使用int来决定要对哪个字段进行排序,您可以执行以下操作:

public static void SortArray(FileData[] fileData, int sortFileNumber = 1)
{
    bool swap;

    do
    {
        swap = false;
        for (int index = 0; index < (fileData.Length - 1); index++)
        {
            bool comparison;

            // Set our comparison to the field sortFileNumber
            if (sortFileNumber == 1)
            {
                comparison = fileData[index].File1Value > fileData[index + 1].File1Value;
            }
            else if (sortFileNumber == 2)
            {
                comparison = fileData[index].File2Value > fileData[index + 1].File2Value;
            }
            else // File3Value becomes default for anything else
            {
                comparison = fileData[index].File3Value > fileData[index + 1].File3Value;
            }

            if (comparison)
            {
                var temp = fileData[index];
                fileData[index] = fileData[index + 1];
                fileData[index + 1] = temp;
                swap = true;
            }
        }
    } while (swap);
}