Find out missing range sequence - asp.net

I have range sequences. I want to find out is their any missing sequence.
let’s say we have 3 margins 0 -25, 25-50, 75-100
so program gives the result as 50 – 75. is missing sequence.

As others have said you should provide at least some code for us to start off with. Also IMO this has nothing to do with ASP.NET.
The following is the solution which might be of help.
I have assumed a few things
The margins which you are getting can be converted to List<string>
There will be always be only 1 margin missing between any 2 margins. i.e. there will never be a case where your 3 margins are 0 -25, 25-50, 100-125 since here consecutive 2 margins are missing 50-75 and 75-100. If this can be a case then please comment so that I can update my answer accordingly
The first margin in the list is always the start margin
Check out the below code
List<string> margin = new List<string>() { "0-25", "25-50", "100-125" };
List<List<int>> splitedMargin = new List<List<int>>();
foreach (var item in margin)
{
var arr = item.Split('-');
splitedMargin.Add(new List<int>() { int.Parse(arr[0]), int.Parse(arr[1]) });
}
//Required missing margin
List<string> missingMargin = new List<string>();
int marginSize = splitedMargin[0][1] - splitedMargin[0][0];
for (int i = 1; i < splitedMargin.Count; i++)
{
if (splitedMargin[i - 1][1] != splitedMargin[i][0])
{
int missingMarginCount = (splitedMargin[i][0] - splitedMargin[i - 1][1]) / marginSize;
if (missingMarginCount == 1)
missingMargin.Add(splitedMargin[i - 1][1].ToString() + "-" + splitedMargin[i][0].ToString());
else
{
for (int j = 0; j < missingMarginCount; j++)
{
missingMargin.Add((splitedMargin[i - 1][1] + (marginSize * j)).ToString() + "-" + (splitedMargin[i - 1][1] + (marginSize * (j + 1))).ToString());
}
}
}
}
Hope this helps

Related

Last line of a datatable asp.net

I have a problem when I'm trying to a loop in a DataTable that a dataset contains.
I'm doing a loop like this:
for(int i = 0; i<ds.Tables[0].Rows.Count - 1 ; i++)
The problem is that I can't get the value of the last line with this one, but if I try to get rid of the "-1" and do a loop on the whole table, I'll have an out of range exception.
This out of range exception is because I have to check if the value of a line "i" is equal to the value of a line "i+1", like this:
if (ds.Tables[0].Rows[i]["Release_No"] != ds.Tables[0].Rows[i + 1]["Release_No"])
So if I do it in a loop, when the index is on the last line it will check if the last line is equal to i+1, and it's out of the table.
So I was trying to check if the index is on the last line, then just get the value of the last line, but it seems like it doesn't work.
if(ds.Tables[0].Rows.IndexOf(ds.Tables[0].Rows[i]) == ds.Tables[0].Rows.Count)
If anyone has an idea, let me know, and of course if it is not clear enough let me know, I'll give more information and more code.
Thanks for your help and your time!
Check if it's the last record, first.
I like to refactor code to read as close to sentence form as possible, explaining what you want it to do using named variables and methods, and that often gets me unlocked.
Try to make each line of code do one thing, and one thing only, like check if it is the last row:
var data = ds.Tables[0].Rows;
var lastRow = data.Count - 1;
for(int i = 0; i < lastRow ; i++)
{
if (i == lastRow){
// This is the last row. Handle the last row here.
}
else
{
// Handle all other rows here
var currentRecord = data[i];
var nextRecord = data[i + 1];
if (currentRecord["Release_No"] != nextRecord["Release_No"])
{
// Handle unique Releases...
}
}
}
Use less than or equal to like this
for(int i = 0; i<=ds.Tables[0].Rows.Count - 1 ; i++)
I hope this may get what you want.
Something like this is better ?
var lastRow = data.Count - 1;
var data = ds.Tables[0].Rows;
for(int i = 0; i< lastRow; i++)
{
testFirstCum = Convert.ToInt32(ds.Tables[0].Rows[i]["EDI_Accum_Quantity"]);
if ( i == lastRow)
{
if (DBNull.Value.Equals(data[i]))
{
quantity = 0;
}
else
{
quantity = Convert.ToInt32(data[i]);
testFirstCum = testFirstCum + quantity;
System.Diagnostics.Debug.WriteLine(quantity);
System.Diagnostics.Debug.WriteLine(testFirstCum);
}
}
else
{
var col = ds.Tables[0].Columns;
var currentRecord = data[i];
var nextRecord = data[i + 1];
if(currentRecord["Release_No"] != nextRecord["Release_No"])
{
for (int j = col[2].Ordinal; j < col.Count; j++)
{
if (DBNull.Value.Equals(data[i][j]))
{
quantity = 0;
}
else
{
quantity = Convert.ToInt32(data[i][j]);
testFirstCum = testFirstCum + quantity;
System.Diagnostics.Debug.WriteLine(quantity);
System.Diagnostics.Debug.WriteLine(testFirstCum);
}
}
}
}
}

Trying to compare multiple consecutive elements of a 2D array of Lables

I have a 2d array of Labels, each label contains a String version of an int. I'm attempting to traverse my array and check to see if each element contains the same int. Am I going about this the wrong way?
public boolean isPattern(Label[][] matirx) {
boolean pattern = false;
for (int rPos = 0; rPos < rows; rPos++) {
for (int cPos = 0; cPos < columns - 3; cPos++) {
if (matrix[cPos][rPos].equals(matrix[cPos + 1][rPos])
&& matrix[cPos][rPos].equals(matrix[cPos + 2][rPos])
&& matrix[cPos][rPos].equals(matrix[cPos + 3][rPos])) {
pattern = true;
}
}
}
When I print my boolean to the output window, I get false no matter what. So I guess my real question is. Am I comparing the contents of each Label or the value at each index, thus causing the variable never to be true?
So I ended up using this solution:
for (int rPos = 0; rPos < rows - 3; rPos++) {
for (int cPos = 0; cPos < columns; cPos++) {
if (matrix[cPos][rPos].getText().equals(matrix[cPos][rPos + 1].getText())
&& matrix[cPos][rPos].getText().equals(matrix[cPos][rPos + 2].getText())
&& matrix[cPos][rPos].getText().equals(matrix[cPos][rPos + 3].getText())) {
pattern = true;
Works as needed. If anyone comes across this and knows a better way, please do share.

Kinect skeleton Scaling strange behaviour

I am trying to scale a skeleton to match to the sizes of another skeleton.
My algoritm do the following:
Find the distance between two joints of the origin skeleton and the destiny skeleton using phytagorean teorem
divide this two distances to find a multiply factor.
Multiply each joint by this factor.
Here is my actual code:
public static Skeleton ScaleToMatch(this Skeleton skToBeScaled, Skeleton skDestiny)
{
Joint newJoint = new Joint();
double distanciaOrigem = 0;
double distanciaDestino = 0;
double fator = 1;
SkeletonPoint pos = new SkeletonPoint();
foreach (BoneOrientation bo in skToBeScaled.BoneOrientations)
{
distanciaOrigem = FisioKinectCalcs.Distance3DBetweenJoint(skToBeScaled.Joints[bo.StartJoint], skToBeScaled.Joints[bo.EndJoint]);
distanciaDestino = FisioKinectCalcs.Distance3DBetweenJoint(skDestiny.Joints[bo.StartJoint], skDestiny.Joints[bo.EndJoint]);
if (distanciaOrigem > 0 && distanciaDestino > 0)
{
fator = (distanciaDestino / distanciaOrigem);
newJoint = skToBeScaled.Joints[bo.EndJoint]; // escaling only the end joint as the BoneOrientatios starts from HipCenter, i am scaling from center to edges.
// applying the new values to the joint
pos = new SkeletonPoint()
{
X = (float)(newJoint.Position.X * fator),
Y = (float)(newJoint.Position.Y * fator),
Z = (float)(newJoint.Position.Z * fator)
};
newJoint.Position = pos;
skToBeScaled.Joints[bo.EndJoint] = newJoint;
}
}
return skToBeScaled;
}
Every seems to work fine except for the hands and foots
Look at this images
I have my own skeleton over me, and my skeleton scaled to the sizes of another person, but the hands and foots still crazy. (but code looks right)
Any suggestion?
It's hard to say without running the code, but it somewhat "looks good".
What I would validate though, is your
if (distanciaOrigem > 0 && distanciaDestino > 0)
If distanciaOrigem is very close to 0, but even just epsilon away from 0, it won't be picked up by the if, and then
fator = (distanciaDestino / distanciaOrigem);
Will result in a very large number!
I would suggest to smooth the factor so it generally fits the proper scale. Try this code:
private static Dictionary<JointType, double> jointFactors = null;
static CalibrationUtils()
{
InitJointFactors();
}
public static class EnumUtil
{
public static IEnumerable<T> GetValues<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
}
private static void InitJointFactors()
{
var jointTypes = EnumUtil.GetValues<JointType>();
jointFactors = new Dictionary<JointType, double>();
foreach(JointType type in jointTypes)
{
jointFactors.Add(type, 0);
}
}
private static double SmoothenFactor(JointType jointType, double factor, int weight)
{
double currentValue = jointFactors[jointType];
double newValue = 0;
if(currentValue != 0)
newValue = (weight * currentValue + factor) / (weight + 1);
else
newValue = factor;
jointFactors[jointType] = newValue;
return newValue;
}
When it comes to factor usage just use the SmoothenFactor method first:
public static Skeleton ScaleToMatch(this Skeleton skToBeScaled, Skeleton skDestiny, double additionalFactor = 1)
{
Joint newJoint = new Joint();
double distanceToScale = 0;
double distanceDestiny = 0;
double factor = 1;
int weight = 500;
SkeletonPoint pos = new SkeletonPoint();
Skeleton newSkeleton = null;
KinectHelper.CopySkeleton(skToBeScaled, ref newSkeleton);
SkeletonPoint hipCenterPosition = newSkeleton.Joints[JointType.HipCenter].Position;
foreach(BoneOrientation bo in skToBeScaled.BoneOrientations)
{
distanceToScale = Distance3DBetweenJoints(skToBeScaled.Joints[bo.StartJoint], skToBeScaled.Joints[bo.EndJoint]);
distanceDestiny = Distance3DBetweenJoints(skDestiny.Joints[bo.StartJoint], skDestiny.Joints[bo.EndJoint]);
if(distanceToScale > 0 && distanceDestiny > 0)
{
factor = (distanceDestiny / distanceToScale) * additionalFactor;
newJoint = skToBeScaled.Joints[bo.EndJoint]; // escaling only the end joint as the BoneOrientatios starts from HipCenter, i am scaling from center to edges.
factor = SmoothenFactor(newJoint.JointType, factor, weight);
pos = new SkeletonPoint()
{
X = (float)((newJoint.Position.X - hipCenterPosition.X) * factor + hipCenterPosition.X),
Y = (float)((newJoint.Position.Y - hipCenterPosition.Y) * factor + hipCenterPosition.Y),
Z = (float)((newJoint.Position.Z - hipCenterPosition.Z) * factor + hipCenterPosition.Z)
};
newJoint.Position = pos;
newSkeleton.Joints[bo.EndJoint] = newJoint;
}
}
return newSkeleton;
}
I also modified your ScaleToMatch method as you see. There was a need to move joints in relation to HipCenter position. Also new positions are saved to a new Skeleton instance so they are not used in further vector calculations.
Experiment with the weight but since our bones length is constant you can use big numbers like 100 and more to be sure that wrong Kinect readings do not disturb the correct scale.
Here's an example of how it helped with scaling HandRight joint position:
The weight was set to 500. The resulting factor is supposed to be around 2 (because the base skeleton was purposely downscaled by a factor of 2).
I hope it helps!

Object reference not set to an instance of an object - but it is?

I am creating a Sudoku Puzzle in asp and I'm having trouble with some classes. When I create a function to display all the numbers in the text box, I get this error: Object reference not set to an instance of an object. I know that it means that my object is null, but here is my code. The line that I am getting the error on is the line that says: stbNumber.setNumber(currentSolution[3 * i + m, 3 * k + n]);
private SudokuTextBox stb;
private Puzzle puzzle;
private Box box;
private Number stbNumber;
public void displayAll(object sender,EventArgs e)
{
puzzle = new Puzzle();
for (int i = 0; i < 3; i++)
{
for (int k = 0; k < 3; k++)
{
box = new Box();
for (int m = 0; m < 3; m++)
{
for (int n = 0; n < 3; n++)
{
stbNumber = new Number();
stb = new SudokuTextBox();
stbNumber.setNumber(currentSolution[3 * i + m, 3 * k + n]);
stb.setTextBoxValue(stbNumber);
stb.setVisibility(true);
box.setItem(stb, m, n);
}// end forth for
}//end third for
puzzle.setItem(box, i, k);
}//end second for
}//end first for
generateBoxes();
}
I have initialized stbNumber at the very top of my code, and I have made sure that currentSolution is not null or empty. I'm therefore unsure as to what I am doing wrong. I also should mention that I have this exact code elsewhere to generate new puzzles and it works just fine, but this section of code specifically gets called when I click a button.
you essentially have 3 possibilities:
stbNumber.setNumber(currentSolution[3 * i + m, 3 * k + n]);
stbNumber could be null
currentSolution could be null
the element you are trying to index could be null--just because currentSolution is not null does not mean the item is at that index is not null--so new one up or take appropriate action
since you new up an instance of stbNumber, it is unlikely to be the culprit (but it could be)
you say you are checking currentSolution is null, I don't see the code for that and from the code you did post it is most likely the culprit here. what you COULD do is add a check for null before you access it, and if your test fails writing an error message somewhere:
stbNumber = new Number();
stb = new SudokuTextBox();
if ( currentSolution != null )
{
// if the item does not exist, new it up
if ( currentSolution[3 * i + m, 3 * k + n] == null ) currentSolution[3 * i + m, 3 * k + n] = new someObject()
stbNumber.setNumber(currentSolution[3 * i + m, 3 * k + n]);
stb.setTextBoxValue(stbNumber);
}
else
{
WriteSomeErrorMessage("currentSolution is null");
}

Tournament Brackets algorithm

I need to create an asp.net page that auto generate a brackets tournament tennis style.
Regarding the managing of match in database, it's not a problem.
The problem is the dynamic graphics creation of brackets.
The user will be able to create tournament by 2-4...32 players.
And i don't know ho to create the graphics bracket in html or gdi...
Using Silverlight, and a Grid, You can produce something like this:
To do it, define a regular UserControl containing a Grid. (This is the default when you build a silverlight app in VS2008 with the Silverlight 3.0 SDK).
Then, add a call to the following in the constructor for the user control:
private void SetupBracket(int n)
{
var black = new SolidColorBrush(Colors.Gray);
// number of levels, or rounds, in the single-elim tourney
int levels = (int)Math.Log(n, 2) + 1;
// number of columns in the Grid. There's a "connector"
// column between round n and round n+1.
int nColumns = levels * 2 - 1;
// add the necessary columns to the grid
var cdc = LayoutRoot.ColumnDefinitions;
for (int i = 0; i < nColumns; i++)
{
var cd = new ColumnDefinition();
// the width of the connector is half that of the regular columns
int width = ((i % 2) == 1) ? 1 : 2;
cd.Width = new GridLength(width, GridUnitType.Star);
cdc.Add(cd);
}
var rdc = LayoutRoot.RowDefinitions;
// in the grid, there is one row for each player, and
// an interleaving row between each pair of players.
int totalSlots = 2 * n - 1;
for (int i = 0; i < totalSlots; i++)
{
rdc.Add(new RowDefinition());
}
// Now we have a grid of the proper geometry.
// Next: fill it.
List<int> slots = new List<int>();
ImageBrush brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri("Bridge.png", UriKind.Relative));
// one loop for each level, or "round" in the tourney.
for (int j = 0; j < levels; j++)
{
// Figure the number of players in the current round.
// Since we insert the rounds in the reverse order,
// think of j as the "number of rounds remaining."
// Therefore, when j==0, playersThisRound=1.
// When j == 1, playersThisRound = 2. etc.
int playersThisRound = (int)Math.Pow(2, j);
int x = levels - j;
int f = (int)Math.Pow(2, x - 1);
for (int i = 0; i < playersThisRound; i++)
{
// do this in reverse order. The innermost round is
// inserted first.
var r = new TextBox();
r.Background = black;
if (j == levels - 1)
r.Text = "player " + (i + 1).ToString();
else
r.Text = "player ??";
// for j == 0, this is the last column in the grid.
// for j == levels-1, this is the first column.
// The grid column is not the same as the current
// round, because of the columns used for the
// interleaved connectors.
int k = 2 * (x - 1);
r.SetValue(Grid.ColumnProperty, k);
int m = (i * 2 + 1) * f - 1;
r.SetValue(Grid.RowProperty, m);
LayoutRoot.Children.Add(r);
// are we not on the last round?
if (j > 0)
{
slots.Add(m);
// Have we just inserted two rows? Then we need
// a connector between these two and the next
// round (the round previously added).
if (slots.Count == 2)
{
string xamlTriangle = "<Path xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' "+
"xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' " +
"Data='M0,0 L 100 50 0 100 Z' Fill='LightBlue' Stretch='Fill'/>";
Path path = (Path)System.Windows.Markup.XamlReader.Load(xamlTriangle);
path.SetValue(Grid.ColumnProperty, 2 * (x - 1) + 1);
path.SetValue(Grid.RowProperty, slots[0]);
path.SetValue(Grid.RowSpanProperty, slots[1] - slots[0] + 1);
this.LayoutRoot.Children.Add(path);
slots.Clear();
}
}
}
}
}
In the above, the connector is just an isosceles triangle, with the apex pointing to the right. It is generated by XamlReader.Load() on a string.
You would also want to pretty it up, style it with different colors and fonts, I guess.
You can insert this silverlight "user control" into any HTML web page, something like embedding a flash app into a page. There are silverlight plugins for IE, Firefox, Opera, Safari, and Chrome.
If you don't want to use Silverlight, you could use a similar approach to construct an HTML table.

Resources