c# - Move list of tables around -
for example, have matrix:
var source = new[] { new[] { "r", "b", "g", "y" }, new[] { "r", "b", "g", "y" }, new[] { "r", string.empty, "g", "y" }, new[] { "r", "b", "g", "y" } }
i want move empty string top position, first, create result equivalent to
var result = new[] { new[] { "r", "string.empty", "g", "y" }, new[] { "r", "b", "g", "y" }, new[] { "r", "b", "g", "y" }, new[] { "r", "b", "g", "y" } }
i want move empty string right, if needed create result equivalent to
var result = new[] { new[] { "r", "g", "y", string.empty }, new[] { "r", "b", "g", "y" }, new[] { "r", "b", "g", "y" }, new[] { "r", "b", "g", "y" } }
here code far
static void moved(list<list<string>> list) { console.writeline("elements:");
checking list
foreach (var sublist in list) { string empty = " "; list[2][2] = empty;
checking sublist , accessing elements in list
(int = 0; < sublist.count; i++) { if (sublist[2] == empty) { sublist[2] = sublist[3]; } }
the value in sublist
foreach (var value in sublist) { console.write(value); console.write(' '); } console.writeline(); } }
here's solution:
class program { static void main(string[] args) { var source = new[,] { { "r", "b", "g", "y" }, { "r", "b", "g", "y" }, { "r", string.empty, "g", "y" }, { "r", "b", "g", "y" } }; printarray(source); move(source, new pos() { row = 2, col = 1 }, new pos() { row = 0, col = 3 }); console.readkey(); } static void move(string[,] arr, pos from, pos to) { movev(arr, from, to); printarray(arr); moveh(arr, from, to); printarray(arr); } // moves item verticaly. static void movev(string[,] arr, pos from, pos to) { // gets distance move. int delta = to.row - from.row; // gets direction of movement (+ or -) int mov = math.sign(delta); // moves item. (int row = from.row, = 0; < math.abs(delta); row += mov, i++) { swap(arr, new pos() { row = row, col = from.col }, new pos() { row = row + mov, col = from.col }); } } // moves item horizonataly. static void moveh(string[,] arr, pos from, pos to) { int delta = to.col - from.col; int mov = math.sign(delta); (int col = from.col, = 0; < math.abs(delta); col += mov, i++) { swap(arr, new pos() { row = to.row, col = col }, new pos() { row = to.row, col = col + mov }); } } // swaps 2 items on each move. static void swap(string[,] arr, pos from, pos to) { string val = arr[to.row, to.col]; arr[to.row, to.col] = arr[from.row, from.col]; arr[from.row, from.col] = val; } // print array console. static void printarray(string[,] arr) { stringbuilder sb = new stringbuilder(); (int = 0; < 4; i++) { sb.appendline(string.format("{0} {1} {2} {3}", getval(arr, i, 0), getval(arr, i, 1), getval(arr, i, 2), getval(arr, i, 3))); } sb.appendline(""); console.write(sb.tostring()); } static string getval(string[,] arr, int row, int col) { return string.isnullorwhitespace(arr[row, col]) ? " " : arr[row, col]; } } struct pos { public int row; public int col; }
edit:
correctend bug (hardcoded from/to) in move
method.
Comments
Post a Comment