Comparing two variable in a structure C# - c#

What I want to do is compare two of the same variable in a structure.
For example I have a structure like so:
struct player
{
public string name;
public int number;
}
static player[] players = new player[3];
and what I want to do is compare the numbers, so that if two players have the same number, something will happen.
This is what I tried, however it would always say two numbers were the same because it would compare two of the same
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
if (players[i].number == players[j].number)
{
Console.WriteLine("Same");
Console.ReadLine();
}
else
{
Console.WriteLine("Not");
Console.ReadLine();
}
}
Hopefully you understand what I mean.
Any help would be really appreciated!
Thanks

Problem is in your loop variables i and j starting both at index zero. Then you are comparing element zero to element zero and therefore the condition is true.
Update this line:
for (int j = 0; j < length; j++)
to this:
for (int j = i + 1; j < length; j++)
Edit
To be more precise. The condition evaluates to true not only for the first element, but for each element when i and j are the same. This solution bars both control variables from having the same value in any iteration.

Simple, just add a check to make sure you aren't comparing the same index, because this is the same object:
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
if (i == j) continue;
if (players[i].number == players[j].number)
{
Console.WriteLine("Same");
Console.ReadLine();
}
else
{
Console.WriteLine("Not");
Console.ReadLine();
}
}

Use a Class, and do it using Linq:
public class Player
{
public string Name { get; set; }
public int Number { get; set; }
}
Then in the other class have this method to cross-check
private void Match()
{
var players = new Player[3].ToList();
foreach (var found in players.ToList().Select(player => players.FirstOrDefault(p => p.Number == player.Number)))
{
if (found != null)
{
Console.WriteLine("Same");
Console.ReadLine();
}
else
{
Console.WriteLine("Not");
Console.ReadLine();
}
}
}

Related

Working with index, local variable and class

In the code below, I am trying to use indexing with item.Number
It looks like I cannot compare if (item.Number[index] == decimalNumbers[j]) like this and getting the error "c# cannot apply indexing with [] to an expression of type 'int'"
If anyone can guide me to the right direction.
Also, code is not a complete code. I just want to understand the reasoning.
public class NumberWithDifference
{
public int Number { get; set; }
public static int[] decimalNumbers = new int[10]{0,1,2,3,4,5,6,7,8,9};
foreach (var item in jagged.Items)
{
i = true;
int index = 0;
var a = item.Number;
for (int j = 0; j < decimalNumbers.Length; j++)
{
if (item.Number[index] == decimalNumbers[j])
{
Console.Write(decimalNumbers[j]);
i = false;
if (index < item.Number.Length - 1)
index++;
}
else
{
Console.Write(0);
}
}
}
As the error message states, item.Number is an int. Indexing can be applied to an array or list of ints, but not to a single int value.
Thus, this code below,
if (item.Number[index] == decimalNumbers[j])
should really be
if (item.Number == decimalNumbers[j])
Assuming jagged is an array of NumberWithDifference, you could also do the following instead:
for (int j = 0; j < decimalNumbers.Length; j++)
{
if (jagged[index].Number == decimalNumbers[j])
{
etc...

How to create an efficient objects activation and deactivation system to progress the game?

I am currently working on a personal project which is an action adventure puzzle game. Basically, there are levels with puzzles involved to challenge the player.
Assume that Level 1 has two stages of puzzles: (Stage 1) Puzzle A, B and C with Clue A, B and C provided. (Stage 2) Puzzle D, E and F with Clue D, E and F provided.
If the respective puzzle is completed, the respective clue will be deactivated, such as Puzzle A has completed, Clue A will be deactivated. Vice versa.
If all Stage 1 puzzles has completed, all Stage 1 puzzles will be deactivated and all Stage 2 puzzles will be activated.
I have tried by hard-coding them. If using array class is a must, is there any way to reduce the redundancy? If not using array class, is there a better way to code?
public class Item
{
public GameObject[] puzzle;
public GameObject[] clue;
public GameObject[] prop;
public GameObject[] puzzleStartNode;
public GameObject[] puzzleEndNode;
public GameObject[] clueNode;
public GameObject[] propNode;
}
public Item[] Stages;
// Start is called before the first frame update
public void ObjectActivation(string stageActivation)
{
//stageOne
if (stageActivation == "StageOne")
{
for (int i = 0; i < Stages[1].clue.Length; i++)
{
Stages[1].clue[i].GetComponent<BoxCollider>().enabled = false;
}
for (int i = 0; i < Stages[1].puzzle.Length; i++)
{
Stages[1].puzzle[i].GetComponent<BoxCollider>().enabled = false;
}
for (int i = 0; i < Stages[1].prop.Length; i++)
{
Stages[1].prop[i].GetComponent<BoxCollider>().enabled = false;
}
for (int i = 0; i < Stages[1].puzzleStartNode.Length; i++)
{
Stages[1].puzzleStartNode[i].GetComponent<BoxCollider>().enabled = false;
}
for (int i = 0; i < Stages[1].puzzleEndNode.Length; i++)
{
Stages[1].puzzleEndNode[i].GetComponent<BoxCollider>().enabled = false;
}
for (int i = 0; i < Stages[1].clueNode.Length; i++)
{
Stages[1].clueNode[i].GetComponent<BoxCollider>().enabled = false;
}
for (int i = 0; i < Stages[1].propNode.Length; i++)
{
Stages[1].propNode[i].GetComponent<BoxCollider>().enabled = false;
}
}
//stageTwo
if (stageActivation == "StageTwo")
{
for (int i = 0; i < Stages[1].clue.Length; i++)
{
Stages[1].clue[i].GetComponent<BoxCollider>().enabled = true;
}
for (int i = 0; i < Stages[1].puzzle.Length; i++)
{
Stages[1].puzzle[i].GetComponent<BoxCollider>().enabled = true;
}
for (int i = 0; i < Stages[1].prop.Length; i++)
{
Stages[1].prop[i].GetComponent<BoxCollider>().enabled = true;
}
for (int i = 0; i < Stages[1].puzzleStartNode.Length; i++)
{
Stages[1].puzzleStartNode[i].GetComponent<BoxCollider>().enabled = true;
}
for (int i = 0; i < Stages[1].puzzleEndNode.Length; i++)
{
Stages[1].puzzleEndNode[i].GetComponent<BoxCollider>().enabled = true;
}
for (int i = 0; i < Stages[1].clueNode.Length; i++)
{
Stages[1].clueNode[i].GetComponent<BoxCollider>().enabled = true;
}
for (int i = 0; i < Stages[1].propNode.Length; i++)
{
Stages[1].propNode[i].GetComponent<BoxCollider>().enabled = true;
}
}
}
What I meant with "teach the item class what it means to activate" was the following. In your Item class add the method SetActive(bool) and let it handle activation/deactivation.
//I'd call it Stage, or the stages field below items for consistency
//but I took your names :D
public class Item
{
//It's kinda better to store the right thing right away
//unless ofc you need the GameObject reference for something you didnt mention
public BoxCollider[] puzzles;
public BoxCollider[] clues;
// ... and so on
public void SetActive(bool activate) {
foreach(var puzzle in puzzles) {
puzzle.enabled = activate;
}
foreach(var clue in clues) {
clue.enabled = activate;
}
// ... same for the other stuff
// Basically, everything that has to do with activation/deactivation
// of the stage goes in here
}
}
When you want to activate/deactivate the stage you can now simply do
public Item[] stages;
public void ObjectActivation(string stageActivation) //I'd use an int tho, see below
{
//stageOne
if (stageActivation == "StageOne") {
stages[0].SetActive(true);
stages[1].SetActive(false);
}
// ...
}
To expand on the comment that I would use int and not string as argument, you could do the following with it
public Item[] stages;
//Arrays are zero indexed, so "StageOne" would actually be id 0
public void ActivateOneStageAndDeactivateTheRest(int stageId) {
for(int i = 0; i < stages.Length; i++) {
stages[i].SetActive(i == stageId);
}
}

Show sublist value from index C#

My problem is I have M subproblem. Each subproblem include x (double array) and reduced cost which has different value for each iteration m. I want to show x which has the minimum reduced cost among all subproblems. here is my class:
public class Subproblem
{
public double[,] x { get; set; }
public double ReducedCost { get; set; }
}
So far, I already can get the minimum Reduced Cost and index of it. Now I want to show x value (double array) which on that index. I've code like this:
var sub = new List<Subproblem>();
for (int m = 0; m < M; ++m)
{
Subproblem s = new Subproblem();
s.x = new double[DC1, DC1];
s.ReducedCost = model.ObjVal;
for (int i = 0; i < DC1; ++i)
{
for (int j = 0; j < DC1; ++j)
{
s.x[i, j] = x[i, j].X;
}
}
sub.Add(s);
}
double minRC = sub.Min(a => a.ReducedCost);
int minRCIndex = sub.FindIndex((i) => i.ReducedCost == minRC);
Console.WriteLine(sub.x(minRCIndex));
the last line (Console.WriteLine(sub.x(minRCIndex));) still got red underline, I don't know how to write it
If you are only trying to get the minimum Reduced Costed subproblem you should be doing:
Subproblem minimumReducedCostedSubproblem = sub[minRCIndex];
And you can print the matrix down like this:
for (int i = 0; i < DC1; ++i)
{
for (int j = 0; j < DC1; ++j)
{
Console.Write(minimumReducedCostedSubproblem.x[i, j] + "\t");
}
Console.Write("\n");
}
But you seem a little confused. You are pushing a Subproblem into your sub list with the same object for M times. Because model.ObjVal doesn't change along the first for loop. There is something wierd going on there too.
It should be
var objWithMinReduceCost = sub[minRCIndex];
//Now you have the object of Subproblem derived from your logic.
//You can access x property of it have further logic to process it.
for (int i = 0; i < DC1; ++i)
{
for (int j = 0; j < DC1; ++j)
{
Console.WriteLine(objWithMinReduceCost.x[i, j]);
}
}
If you are interested in obtaining the double array, you could just do this:
double[,] result = sub.First(i => i.ReducedCost == minRC).x;
Although as Tolga mentioned, all your elements will have the same ReducedCost with your current code.

Many else and if statements?

I am reading a csv file which has column names in first line and values in line >1. I need to get the position of the column name. The only way I can think of is to do either switch or ifs. I read it somewhere that in my case , it is faster (better) to do the ifs. However the file has many columns (~120). Just wondering if there is an alternative(s).
private static void Get_Position(string line, performance p)
{
string[] line_split = line.Split(',');
for (int i = 0; i < line_split.Length; i++)
{
if (line_split[i].Contains(#"(0)\% Processor Time"))
{
p.percore[0] = i;
}
else if (line_split[i].Contains(#"(1)\% Processor Time"))
{
p.percore[1] = i;
}
else if (line_split[i].Contains("Private Bytes"))
{}
else if (line_split[i].contains("DPC")
{
}
//on and on and on with else ifs
What is preventing you from using a loop?
for (int i = 0; i < line_split.Length; i++)
{
for(var j = 0; j < 120; j++)
{
if(line_split[i].Contains(#"(" + j + ")\% Processor Time"))
{
p.percore[j] = i;
}
}
...
To maintain the same functionality as if else if then you could use a break inside the conditional.
Edit: The edit now made it clear that there is no clear pattern to the string in contains. Still, if you are writing out 120 if/else if statements you should store what you will be looking for in some type of collection. For example, a List would work. Then access the index j of the collection in your loop:
...
var listOfSearchItems = new List<string>() { "Private Bytes", "DPC" };
for (int i = 0; i < line_split.Length; i++)
{
for(var j = 0; j < 120; j++)
{
if(line_split[i].Contains(listOfSearchItems[j])
{
p.percore[j] = i;
}
}
...

2 dimensional array

For each element in the array I need a unique identifier such as Seat1, Seat2, Seat 3....... all the way to the end of the length of the array.
currently I have done the following:
int rows = 10, cols = 10;
bool[ , ] seatArray = new bool[rows , cols]; //10 rows, 10 collums
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++ )
{
seatArray[i, j] = false;
}
foreach (bool element in seatArray)
{
Console.WriteLine("element {0}", element);
}
}
this simply just says "Element False" x 100 in the console.
i need to replace "Element" with Seat1, Seat2, Seat3....to the end of the array length.
any help will be much appreciated!
thank you!
Create a Seat class (or structure, if more appropriate) with ID and Occupied(?) properties. Make an array of this type.
public class Seat
{
public string ID { get; set; }
public bool Occupied { get; set; }
}
int rows = 10, cols = 10;
Seat[,] seats = new Seat[rows,cols];
for (int i = 0; i < rows; ++i )
{
for (int j = 0; j < cols; ++j)
{
seats[i,j] = new Seat { ID = "Seat" + (i*cols + j), Occupied = false };
}
}
foreach (var seat in seats)
{
Console.WriteLine( "{0} is{1} occupied", seat.ID, seat.Occupied ? "" : " not" );
}
int count = 1;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++ )
{
seatArray[i, j] = count;
count++;
}
foreach (bool element in seatArray)
{
Console.WriteLine("element {0}", element);
}
no idea what language this is so idk the syntax but just do some external counter to number them
that just says false every time you set every one to false, dont use a bool, or write a class to hold the true false and number info
tvanfosson, i am struggling to make your coding work, iv put it into a new class off my main method see below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Class1
{
public class Seat
{
public string ID { get; set; }
public bool Occupied { get; set; }
}
int rows = 10, cols = 10;
Seat[,] seats = new Seat[rows,cols];
for (int i = 0; i < rows; ++i )
{
for (int j = 0; j < cols; ++j)
{
seats[i,j] = new Seat { ID = "Seat" + (i*cols + j), Occupied = false };
}
}
foreach (var seat in seats)
{
Console.WriteLine( "{0} is{1} occupied", seat.ID, seat.Occupied ? "" : " not" );
}
}
}
is this correct as i seem to be receiving a lot of syntax errors
thank you!

Categories

Resources