DataTable dynamic computed column - c#

I need a way to update a calculated Datatable's Column base on string in other string column.
for example:
x y FormulaCol ComputedCol
------------------------------ -----------
2 5 x+y 7
2 5 x*y 10
i know that i can use a for loop and calculate result column:
for (int i = 0; i < DT.Rows.Count; i++){
string formula=DT.Rows[i]["FormulaCol"].ToString().Replace("x",DT.Rows[i]["x"]).Replace("y",DT.Rows[i]["y"])
DT.Rows[i]["ComputedCol"] =(int)DT.Compute(formula , "")
}
Is there any better way?

If you don't want to use loop, try this...
DT = DT.AsEnumerable()
.Select(
row =>
{
row["ComputedCol"] = (int)DT.Compute(row["FormulaCol"].ToString()
.Replace("x", row["x"].ToString())
.Replace("y", row["y"].ToString()), "");
return row;
}
).CopyToDataTable<DataRow>();

A simple but long solution:
This is how your table will look like,
x y FormulaCol ComputedCol
------------------------------ -----------
2 5 + 7
2 5 * 10
and your code:
for (int i = 0; i < DT.Rows.Count; i++){
switch(DT.Rows[i]["FormulaCol"].ToString()){
case "+":
int formula=(int) DT.Rows[i]["x"] + (int) DT.Rows[i]["y"];
DT.Rows[i]["ComputedCol"] = formula;
break;
case "-":
int formula=(int) DT.Rows[i]["x"] - (int) DT.Rows[i]["y"];
DT.Rows[i]["ComputedCol"] = formula;
break;
case "*":
int formula=(int) DT.Rows[i]["x"] * (int) DT.Rows[i]["y"];
DT.Rows[i]["ComputedCol"] = formula;
break;
case "/":
int formula=(int) DT.Rows[i]["x"] / (int) DT.Rows[i]["y"];
DT.Rows[i]["ComputedCol"] = formula;
break;
}
}
Hope this helps!

for (int i = 0; i < DT.Rows.Count; i++){
string formula=DT.Rows[i]["FormulaCol"].ToString()
for (int j = 0; j < DT.Columns.Count; j++){
furmula=formula.Replace(DT.Columns[j].Name ,DT.Rows[i][j].ToString())
}
DT.Rows[i]["ComputedCol"] =(int)DT.Compute(formula , "")
}

Related

c# recursion for matrix column combinations

I have MxN matrix with K groups. Group is a set of column. How I can generate combnations of columns of one group with other?
For example 2x4 matrix, group size - 2 columns (1,2 - first, 3,4 - second)
And I get combinations
1 - 3
1 - 4
2 - 3
2 - 4
In this case I can use multiple loop
for (int i = 0; i < 2; i++)
for (int j = 2; j < 4; j++)
Console.WriteLine("{0} - {1}", i, j);
How about the case with 3 groups and 2x6 matrix?
for (int i = 0; i < 2; i++)
for (int j = 2; j < 4 ; j++)
for (int k = 4; k < 6; k++)
Console.WriteLine("{0} - {1} - {2}", i, j, k);
How about other cases? How to organize a cycle/recursion?
Not sure about edge cases and role of rows in this question, but for simple cases you provided this will work:
static void Main()
{
var columns = 6;
var groupSize = 2;
var groups = GetGroups(columns, groupSize).ToArray();
var groupCurrentIndex = Enumerable.Range(0, groups.Length).ToDictionary(i => i, i => 0);
var maxIndex = groupSize - 1;
while (true)
{
var combination = groups.Select((g, i) => g[groupCurrentIndex[i]]);
PrintCombination(combination);
var incrementedGroupIndex = false;
for (var i = groups.Length - 1; i > 0; i--)
{
if (groupCurrentIndex[i] != maxIndex)
{
groupCurrentIndex[i]++;
incrementedGroupIndex = true;
break;
}
if (groupCurrentIndex[i] == maxIndex && groupCurrentIndex[i - 1] != maxIndex)
{
groupCurrentIndex[i-1]++;
incrementedGroupIndex = true;
for (var j = i; j < groups.Length; j++)
{
groupCurrentIndex[j] = 0;
}
break;
}
}
if (!incrementedGroupIndex)
{
break;
}
}
Console.ReadLine();
}
private static IEnumerable<int[]> GetGroups(int columns, int groupSize)
{
for (var startIndex = 0; startIndex < columns; startIndex = startIndex + groupSize)
{
yield return Enumerable.Range(startIndex, groupSize).ToArray();
}
}
private static void PrintCombination(IEnumerable<int> combination)
{
Console.WriteLine(string.Join(" - ", combination));
}

Even number's sum from an integer

How to get the even number' sum from an integer input.
var intInput = 10;
Now i want the even' sum. In this case = 2+4+6+8+10 = 30
var evenCount = 0;
if (i % 2==0)
{
evenCount = evenCount + i;
}
How to achieve this?
var evenCount = (intInput / 2) * (intInput / 2 + 1);
This is just twice the sum of all the integers from zero to half the specified number.
2+4+6+8+10 = 2 (1+2+3+4+5)
How about this?
var sum = Enumerable.Range(1,10).Where(x=> x%2==0).Sum();
int intInput=10;
var evenCount = 0;
for (int i=1;i<=intInput;i++)
{
if (i % 2==0)
{
evenCount = evenCount + i;
}
}
Try
var intInput =10;
var evenValueSum = 0;
for(int i=intInput ;i>0;i--)
{
if(i %2 ==0)
{
evenValueSum += i;
}
}
int end = inputNum / 2;
int sum = 0;
for(int i = 1; i <= end; i++)
sum += i * 2;
int evenCount = 0;
int countFrom = 1;
int countTo = 10;
for (int i = countFrom; i <= countTo; i++) {
if (i % 2 == 0) {
evenCount += i
}
}

Merge two table in new table with random records of two tables - c#

I have 2 tables with one column in sql and I want to merge data into one new table which have 2 columns,
First table has one row and second row should go 'V86'
2nd table has one row and second row should go 'V2T'
I need to merge 700 records total in new table 328 from first table and 372 from 2nd table. there should be 2 sets 350 each with 164 record from first table and 186 records from second table with good randomness of records.
I wrote this code first batch of 350 records have nice randomness but second batch of 350 has 1-164 'V86' records and 165-350 'V2T' [No Randomness]
its the same loop which runs twice, I tried but couldn't figure it out. Can anyone help me out?
private void QUEMerge()
{
DataTable ae50braQUE = aeBL.AE50BraQUE();
DataTable ae50SwimQUE = aeBL.AE50SwimQUE();
int rowAE50BraQue = 0;
int rowAE50SwimQue = 0;
int a = 0;
int b = 0;
int ttlque = 0;
for (int i = 0; i < 2; i++)
{
int temp1 = 0;
int temp2 = 0;
for (int j = 0; j < 350; j++)
{
rowAE50BraQue = rowAE50BraQue + 3;
rowAE50SwimQue = rowAE50SwimQue + 4;
for (; a < rowAE50BraQue; a++)
{
if (temp1 >= 164 || ttlque >= 700)
{
break;
}
DataRow dr = ae50braQUE.Rows[a];
aeBL.MergeQUE(dr["Coupon"].ToString(), "V86");
temp1++;
ttlque++;
}
for (; b < rowAE50SwimQue; b++)
{
if (temp2 >= 186 || ttlque >= 700)
{
break;
}
DataRow dr = ae50SwimQUE.Rows[b];
aeBL.MergeCouponsQUE(dr["Coupon"].ToString(), "V2T");
temp2++;
ttlque++;
}
}
}
}
You can do this using only t-sql:
WITH cte as
(
SELECT a.a, b.b, ROW_NUMBER() OVER(PARTITION BY a.a ORDER BY NEWID()) as rn
FROM (VALUES ('x'),('y'),('z')) AS a(a)
CROSS JOIN (VALUES ('a'),('b'),('c'),('d')) as b(b)
)
--INSERT INTO NewTable(a, b)
SELECT TOP(5) a, b
FROM cte
WHERE rn in (1,2)
ORDER BY NEWID();
where a - table1, b - table2, TOP(5) - in your case TOP(700)
p.s. this query is completely independent, so you can run it to test results
This is my fixed working code..
private void QUEMerge()
{
DataTable ae50braQUE = aeBL.AE50BraQUE();
DataTable ae50SwimQUE = aeBL.AE50SwimQUE();
int x = 0;
int y = 0;
//int ttlque = 0;
for (int i = 0; i < 2; i++)
{
int rowAE50BraQue = 0;
int rowAE50SwimQue = 0;
int a = 0;
int b = 0;
int temp1 = 0;
int temp2 = 0;
for (int j = 0; j < 350; j++)
{
rowAE50BraQue = rowAE50BraQue + 3;
rowAE50SwimQue = rowAE50SwimQue + 4;
for (; a < rowAE50BraQue; a++)
{
if (temp1 >= 164)
{
break;
}
DataRow dr = ae50braQUE.Rows[x];
aeBL.MergeCouponsQUE(dr["Coupon"].ToString(), "V86");
temp1++;
x++;
//ttlque++;
}
for (; b < rowAE50SwimQue; b++)
{
if (temp2 >=186)
{
break;
}
DataRow dr = ae50SwimQUE.Rows[y];
aeBL.MergeCouponsQUE(dr["Coupon"].ToString(), "V2T");
temp2++;
y++;
// ttlque++;
}
}
}

Creating a 3x3 Matrix and ordering numbers in a vortex from smaller to bigger

i would like to create a 3x3 matrix with input numbers and then orders number from smaller to bigger and place it in the matrix like a vortex like : 1,2,3,4,5,6,7,8,9 and place number 1 to 0.0 position,2 to 0.1, 3 to 0.2, 4 to 1.2, 5 to 2.2, 6 to 2.1, 7 to 2.0, 8 to 1.0 and 9 to 1.1.
const int MATRIX_ROWS = 3;
const int MATRIX_COLUMNS = 3;
List<int> l = new List<int>(l);
double[,] matrix = new double[MATRIX_ROWS, MATRIX_COLUMNS];
for (int i = 0; i < MATRIX_ROWS * MATRIX_COLUMNS; ++i)
{
int input;
Console.Write("Enter value");
while (!int.TryParse(Console.ReadLine(), out input))
{
Console.Write("Enter correct value!");
}
l.Add(input);
}
l.Sort();
for (int i = 0; i < MATRIX_ROWS; i++)
{
for (int j = 0; j < MATRIX_COLUMNS; j++)
{
matrix[i, j] = l[i * 3 + j];
}
I start like that to get input numbers and i would like help for the second part.
this will present you with the "vortex like" result for the matrix:
List<int> nums = new List<int>();
double[,] matrix = new double[3,3];
for (int i = 0; i < 9; ++i)
{
double input;
Console.Write("Enter value");
while (!double.TryParse(Console.ReadLine(), out input))
{
Console.Write("Enter correct value!");
}
nums.Add(int.Parse(input.ToString()));
}
nums.Sort();
int block = 0;
int[] order = new int[] { 0, 1, 2, 2, 2, 1, 0, 0, 1 };
for (int i = 0 ; i < order.Length; i++)
{
switch (block)
{
case 0:
matrix[block, order[i]] = nums[i];
if (i == 2)
block = 1;
break;
case 1:
if (i < order.Length - 3)
{
matrix[block, order[i]] = nums[i];
block = 2;
}
else
matrix[block, order[i]] = nums[i];
break;
case 2:
if(i == order.Length - 3)
{
matrix[block, order[i]] = nums[i];
block = 1;
}
else
matrix[block, order[i]] = nums[i];
break;
}
}
Console.WriteLine("The Resulting Matrix is:");
for (int row = 0, col = 0; row < 3; row++)
{
Console.WriteLine("row " + row + ": {0} - {1} - {2}", matrix[row, col], matrix[row, col + 1], matrix[row, col + 2]);
col = 0;
}
EDIT:now it displays the results.
As I see it - you can declare a List<int> l somewhere at the beginning, read the whole data by l.Add(x); then perform l.Sort() and after the data is sorted - populate your matrix. Let me know if you have further questions.
So you will get something like
const int MATRIX_ROWS = 3;
const int MATRIX_COLUMNS = 3;
List<int> l = new List<int>();
double[,] matrix = new double[MATRIX_ROWS, MATRIX_COLUMNS];
for (int i = 0; i < MATRIX_ROWS * MATRIX_COLUMNS; ++i)
{
double input;
Console.Write("Enter value");
while (!double.TryParse(Console.ReadLine(), out input))
{
Console.Write("Enter correct value!");
}
l.Add(input);
}
l.Sort();
for (int i = 0; i < MATRIX_ROWS; i++)
{
for (int j = 0; j < MATRIX_COLUMNS; j++)
{
matrix[i, j] = l[i*3 + j];
}
}

Tic-Tac-Toe programming

I'm trying to create a program for homework that displays a Tic-Tac-Toe board, and when the user clicks the button it displays a random number in all of the boxes. The number 1 = "X" and 0 = "O". I created 9 labels labeled "label1, label2...etc". Once the labels are full, I need to display who won, the letter X or O. I'm using arrays for this but am kinda of lost at this point. what do I need to do to display the random numbers into the labels. Here is the code I've written for the click event handler so far.
Random rand = new Random(2);
int click;
click = rand.Next(2);
const int ROWS = 3;
const int COLS = 3;
int[,] letters = new int[ROWS,COLS];
int ROW = ROWS;
int COL = COLS;
for (int row = 0; row < ROWS; ROW ++) {
for (int col = 0; col < COLS; COL ++) {
letters[row, col] = rand.Next(2);
int X = 1;//???
int O = 0;//???
label1.Text = [ROW,COL].ToString();//???
}
}
Here an attempt at an explanation:
first, you have the data to represent your problem:
const int ROWCOUNT = 3;
const int COLCOUNT = 3;
private int[,] letters = new int[ROWCOUNT,COLCOUNT];
Random rand = new Random(DateTime.Now.Ticks);
then you want to randomly fill that data:
private void randomize()
{
for( int row = 0; row < ROWCOUNT; row++ ){ //start with row=0, do row=row+1 until row no longer < ROWCOUNT
for( int col = 0; col < COLCOUNT; col++ ){
letters[row,col] = rand.nextInt(2);
}
}
}
finally, you want to display the array somewhere (in your case labels):
//These need to be added to a GridLayoutManager
private JLabel[,] labels = new JLabel[ROWCOUNT,COLCOUNT];
private void updateView(){
for( int row = 0; row < ROWCOUNT; row++ ){ //start with row=0, do row=row+1 until row no longer < ROWCOUNT
for( int col = 0; col < COLCOUNT; col++ ){
var current = letters[row,col];
var labelText = "O";
if( current > 0 )
labelText = "X";
labels[row,col].Text = labelText;
}
}
}
so, when the user clicks the button, you call:
randomize();
updateView();
hope it helps
from your comments, it seems setting the Label Text needs more explanation:
var labelText = "O";
if( current > 0 )
labelText = "X";
labels[row,col].Text = labelText;
maybe, i should have written it more like this:
String textForLabel = "O"; //0 represents O, 1 represents X
//test to see, if it really is a 0, not a 1
if( current != 0 ){
//oh, it is not a zero, therefore, set
textForLabel = "X";
}
JLabel labelAtRowAndCol = labels[row,col];
labelAtRowAndCol.Text = textForLabel;
I refuse to provide you the exact answer since you learning how to dot his is the entire point of this excerise.
Before I started the game I would randomly choose the first move: X or O.
I would then do the following:
1) I would place all the Labels into a collection.
2) I would randomly choose one of the Labels within the collection and change the Text property.
3) I would then remove the same Label from the collection
4) Rinse and Repeat.
You DO NOT need a two diminsional array for this.
In order to figure out the winner...I would keep track of the moves of each player. There is only a static number of winning moves in this game. Would be a simple task to determine if there were three X's in the top row or not.
#include<iostream>
#include<iomanip>
#include<set>
using namespace std;
char s[3][3] = {{'*','*','*'},{'*','*','*'},{'*','*','*'}};
void show(char os[3][3]);
int def[9];
void changeo(int n);
void changex(int n);
int stop();
set<int> cset;
int search (int n){
}
int main(){
int n; show(s);
int ss = 2;
cout<<endl;
while (stop()){
if (ss%2==0){
cout<<"player One(O) : enter n "; cin>>n;
if (!cset.count(n) && n<10){
cset.insert(n);
changeo(n);
show(s);
ss++;
}
else{
cout<<"invalid move"<<endl;
}
}
else{
cout<<"player Two(X) : enter n "; cin>>n;
if (!cset.count(n)&& n<10){
cset.insert(n);
changex(n);
show(s);
ss++;
}
}
}
cout<<"\nyou can see the winner"<<endl;
cout<<"your moves are "<<ss;
return 0;
}
void show(char s[3][3]){
cout<< setw(7)<< "1: " <<s[0][0]<<setw(5)<<"2: " <<s[0][1]<<setw(5)<<"3: " <<s[0][2]<<endl;
cout<< setw(7)<< "4: " <<s[1][0]<<setw(5)<<"5: " <<s[1][1]<<setw(5)<<"6: " <<s[1][2]<<endl;
cout<< setw(7)<< "7: " <<s[2][0]<<setw(5)<<"8: " <<s[2][1]<<setw(5)<<"9: " <<s[2][2]<<endl;
cout<<endl;
}
void changeo(int n){
switch(n){
case 1:
s[0][0] = 'O';
break;
case 2:
s[0][1] = 'O';
break;
case 3:
s[0][2] = 'O';
break;
case 4:
s[1][0] = 'O';
break;
case 5:
s[1][1] = 'O';
break;
case 6:
s[1][2] = 'O';
break;
case 7:
s[2][0] = 'O';
break;
case 8:
s[2][1] = 'O';
break;
case 9:
s[2][2] = 'O';
break;
}
}
void changex(int n){
switch(n){
case 1:
s[0][0] = 'X';
break;
case 2:
s[0][1] = 'X';
break;
case 3:
s[0][2] = 'X';
break;
case 4:
s[1][0] = 'X';
break;
case 5:
s[1][1] = 'X';
break;
case 6:
s[1][2] = 'X';
break;
case 7:
s[2][0] = 'X';
break;
case 8:
s[2][1] = 'X';
break;
case 9:
s[2][2] = 'X';
break;
}
}
int stop(){
int m=0;
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
if(s[i][j]=='*'){
m=1;
break;
}
}
}
return m;
}

Categories

Resources