Calculating assignemnt operators - math

Can someone explain to me why the answer to this problem isn't 25,102?
For the following code, suppose the if statement is true 50% of the time. If so, how many assignment operations occur? (Don't forget to count the initializations of i and j. Also remember that i++ and j++ are assignments.)
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
if (arr[j] < arr[i]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

I can see how you got 25102, but I think you've not counted the j loop properly - it doesn't just add one j=0 to the total because the whole loop happens multiple times.

Related

How would this shell-sort algorithm be coded in recursive?

I understand that any iterative function can be written recursively, but I still don't quite understand how to write it as a recursive function.
This function receives an array (elements) and a int (number of elements), and sorts them from lower to higher, but I don't get how to make it recursive, any help would be appreciated!
void ShellSort(int *arr, int num){
for (int i = num / 2; i > 0; i = i / 2)
{
for (int j = i; j < num; j++)
{
for(int k = j - i; k >= 0; k = k - i)
{
if (arr[k+i] >= arr[k])
{
break;
}
else
{
arr[k]=arr[k] + arr[k+i];
arr[k+i]=arr[k] - arr[k+i];
arr[k]=arr[k] - arr[k+i];
}
}
}
}
return ;
}

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);
}
}
}
}
}

Firebase (....ContinueWith(task => ...) in a For-Loop

First, this is the code:
for (int j = 1; j <= count; j++)
{
db.Child("Some Child").GetValueAsync().ContinueWith(task =>
{
Debug.Log("j: " + j); // Here the Debug will show me that j = count
if (task.IsFaulted)
{
// ERROR HANDLER
}
else if (task.IsCompleted)
{
// Some Code Here
}
});
}
Ok, so my problem is that after the "....ContinueWith(task => ..." ' j ' will become directly equal to the count variable. Why this happens and how to solve it? Or is there another method to do that?
Ok, so my problem is that after the "....ContinueWith(task => ..." ' j
' will become directly equal to the count variable. Why this happens
and how to solve it?
That's because you used <= instead of <. With <=, j must be equals to count for the loop condition to be met and finish. If you want j to be less than count then use count-1 or simply use <.
So, that should be
for (int j = 1; i <= count-1; j++)
Or
for (int j = 1; i < count; j++)
Note that array starts from 0 not 1 so int j = 1; should be int j = 0; but I have a feeling that's what you wanted to do and you are starting the loop from 1 on purpose.
Finally, another problem is your variable being captured in a loop because you are using lambda in the ContinueWith function. See this post for more information. To use the j variable inside the ContinueWith lambda function, make a copy of it then use that copy instead of the j variable.
db.Child("Some Child").GetValueAsync().ContinueWith(task =>
{
//MAKE A COPY OF IT
int jCopy = j;
Debug.Log("j: " + jCopy); // Here the Debug will show me that j = count
}
Complete fixed code:
for (int j = 1; i < count; j++)
{
db.Child("Some Child").GetValueAsync().ContinueWith(task =>
{
//MAKE A COPY OF IT
int jCopy = j;
Debug.Log("j: " + jCopy);
if (task.IsFaulted)
{
// ERROR HANDLER
}
else if (task.IsCompleted)
{
// Some Code Here
}
});
}

Visible columns in Treetableview

In javaFx, treetableView, we can hide or show columns using "+" i.e
setTableMenuButtonVisible(true) symbol
say I have 10 columns in treetableview, but i have shown only 5, How can my program get count of only those columns which are visible (i.e 5 in this case)
U can have something like
ObservableList<TableColumn> visibleColumnList =FXCollections.observableArrayList();
ObservableList<TableColumn > tableColumnList = tableView.getColumns();
for (int j = 0; j < tableColumnList.size(); j++) {
TableColumn tableCol = tableColumnList.get(j);
if (tableCol.isVisible())
visibleColumnList.add(tableCol);
}
Long count = visibleColumnList.size();
Thanks Dev for your answer, though tableCol.isVisible method doesnt works for me, but i got it done other way round.
int count=0;
for (int j = 0; j < ltpSystemViewer.getTable().getColumnCount(); j++) {
TableColumn tableCol = ltpSystemViewer.getTable().getColumn(j);
if (tableCol.getWidth()>0)
count++;
}
return count;

how to make a map in xna 4 with matrix from text file

I am trying to make a map by reading a text file line by line (because i cant find how to do that word by word). So I make a map00.txt that looks like "33000000111" (every number is one row, first 2 rows are number of columns and rows so matrix that I load it into looks like
000
000
111
). Now I am supposed to draw 3 tiles at the bottom (1=draw tile). I do so by drawing tile at its position in matrix * window height(width) / matrix number of rows(columns).
PROBLEM: i cant get the right parameters for current window width and height.
Code for loading tiles:
public int[,] LoadMatrix(string path)
{
StreamReader sr = new StreamReader(path);
int[,] a = new int[int.Parse(sr.ReadLine().ToString()),
int.Parse(sr.ReadLine().ToString())];
for(int i = 0; i < a.GetLength(0); i++)
for (int j = 0; j < a.GetLength(1); j++)
{ a[i, j] =int.Parse(sr.ReadLine().ToString()); }
sr.Close();
return a;
}
Code for drawing tiles:
public void DrawTiles(SpriteBatch sp, GraphicsDeviceManager gdm)
{
for(int i = 0; i < matrix.GetLength(0); i++)
for(int j = 0; j < matrix.GetLength(1); j++)
{
if (i == 1)
{
sp.Draw(tile,
new Rectangle(j * (gdm.PreferredBackBufferWidth / 3),//matrix.GetLength(1),
i * (gdm.PreferredBackBufferWidth / 3),//matrix.GetLength(0),
gdm.PreferredBackBufferWidth / matrix.GetLength(1),
gdm.PreferredBackBufferHeight / matrix.GetLength(0)),
Color.White);
}
}
}
but the result is that they are drawn about 40 pixels above the bottom of the screen!
and i tried with GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height(Width) but i get the same result. And when i put calculated numbers that should (in theory) be width/columns and heigth/rows i get what i want. So any suggestions would be VERY appriciated because i am stuck at this for a long time on google and Stack Overflow.
Here is a reworked version of your Draw code, which should work:
public void DrawTiles(SpriteBatch sp, GraphicsDeviceManager gdm)
{
//You would typically pre-compute these in a load function
int tileWidth = gdm.PreferredBackBufferWidth / matrix.GetLength(0);
int tileHeight = gdm.PreferredBackBufferWidth / matrix.GetLength(1);
//Loop through all tiles
for(int i = 0; i < matrix.GetLength(0); i++)
{
for(int j = 0; j < matrix.GetLength(1); j++)
{
//If tile value is not 0
if (matrix[i,j] != 0)
{
sp.Draw(tile, new Rectangle(i * tileWidth, j * tileHeight, tileWidth, tileHeight), Color.White);
}
}
}
}

Resources