Skip to content

Instantly share code, notes, and snippets.

@amantix
Created February 26, 2018 11:14
Show Gist options
  • Save amantix/9ca61020d0a24d18bbefe4df17fd0f3e to your computer and use it in GitHub Desktop.
Save amantix/9ca61020d0a24d18bbefe4df17fd0f3e to your computer and use it in GitHub Desktop.
Read names (lines of text) from text file, permute them and write result to another text file.
using System;
using System.Collections.Generic;
using System.IO;
namespace AssignmentRandomizer
{
class Program
{
static void Main()
{
var names = File.ReadAllLines("names.txt");
var permutation = GetRandomPermutation(names);
File.WriteAllText("permutation.txt",string.Join('\n',permutation));
}
private static IEnumerable<T> GetRandomPermutation<T>(IList<T> names)
{
var rnd = new Random();
names=new List<T>(names);
for (int i = 0; i < names.Count; i++)
{
int choice = i+rnd.Next(names.Count-i);
Swap(names, i, choice);
}
return names;
}
private static void Swap<T>(IList<T> items, int i1, int i2)
{
var tmp = items[i1];
items[i1] = items[i2];
items[i2] = tmp;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment