C# enter value into multidimensional array - c#

I am build a program with c#, and have included dataGridView on it. I do math operation on that dataGridView data, then insert the result into multidimensional array. But i got error message that say "Object reference not set to an instance of an object".
here my code:
frm_clustering.cs
public void hitungMatriksJarak()
{
clusteringModel cm = new clusteringModel();
int i = 0;
int j = 0;
for (i = 0; i < this.dgv_clustering.Rows.Count; i++)
{
for (j = 0; j < this.dgv_clustering.Rows.Count; j++)
{
cm.matriks[j,i] = Math.Sqrt(Math.Pow(Convert.ToDouble(this.dgv_clustering[1, i].Value), 2) +
Math.Pow(Convert.ToDouble(this.dgv_clustering[2, i].Value), 2) +
Math.Pow(Convert.ToDouble(this.dgv_clustering[3, i].Value), 2) +
Math.Pow(Convert.ToDouble(this.dgv_clustering[4, i].Value), 2));
}
}
}
clusteringModel.cs:
class clusteringModel
{
private int _jmlKel;
public int jmlKel
{
get { return _jmlKel; }
set { _jmlKel = value; }
}
private double[,] _matriks = new double[500,500];
public double[,] matriks
{
get { return _matriks; }
set { _matriks = value; }
}
}

Related

Add another item in array without built-in functions

The following script is working fine. But need to add one more item in array without built-in function. Is it possible to do without Resize() ?
string[] data = {"item-1", "item-2"};
Array.Resize(ref data, 3);
data[2] = "item-3";
foreach(string i in data) {
Console.WriteLine(i);
}
No. Arrays are fixed size, so the only way to add more stuff to them is to resize them.
If you have a scenario where you need to add a dynamic number of elements, use List<T> instead.
Assuming you're trying to increase the size of an array without any built-in libraries or data structures, you just need to create a new larger array, copy the old elements, then add your new element.
string[] data = {"item-1", "item-2"};
string[] newData = new string[data.Length + 1];
int i;
for (i = 0; i < data.Length; i++) {
newData[i] = data[i];
}
newData[i] = "item-3";
Console.WriteLine(newData[2]);
The short answer is no. But if you want you can always implement a logic that does the resizing. You could do something like this implementation of a List:
public class List<T> : IAbstractList<T>
{
private const int DEFAULT_CAPACITY = 4;
private T[] _items;
public List()
: this(DEFAULT_CAPACITY) {
}
public List(int capacity)
{
if (capacity < 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity));
}
this._items = new T[capacity];
}
public T this[int index]
{
get
{
this.ValidateIndex(index);
return this._items[index];
}
set
{
this.ValidateIndex(index);
this._items[index] = value;
}
}
public int Count { get; private set; }
public void Add(T item)
{
this.GrowIfNecessary();
this._items[this.Count++] = item;
}
public bool Contains(T item)
{
for (int i = 0; i < this.Count; i++)
{
if (this._items[i].Equals(item))
{
return true;
}
}
return false;
}
public int IndexOf(T item)
{
for (int i = 0; i < this.Count; i++)
{
if (this._items[i].Equals(item))
{
return i;
}
}
return -1;
}
public void Insert(int index, T item)
{
this.ValidateIndex(index);
this.GrowIfNecessary();
for (int i = this.Count - 1; i > index; i--)
{
this._items[i] = this._items[i - 1];
}
this._items[index] = item;
this.Count++;
}
public bool Remove(T item)
{
var index = this.IndexOf(item);
if (index == - 1)
{
return false;
}
this.RemoveAt(index);
return true;
}
public void RemoveAt(int index)
{
this.ValidateIndex(index);
for(int i = index; i < this.Count - 1; i++)
{
this._items[i] = this._items[i + 1];
}
this._items[this.Count - 1] = default;
this.Count--;
}
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < this.Count; i++)
{
yield return this._items[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
=> this.GetEnumerator();
private void ValidateIndex(int index)
{
if (index < 0 || index >= this.Count)
{
throw new IndexOutOfRangeException(nameof(index));
}
}
private void GrowIfNecessary()
{
if (this.Count == this._items.Length)
{
var array = new T[this.Count * 2];
Array.Copy(this._items, array, this._items.Length);
this._items = array;
}
}
}
The above sample code can give you ideas about implementing other methods that need array resizing as well.

Can't get extended label class to show in windows forms application

I currently have a class that extends the System.Windows.Forms.Label class. I'm looking to program minesweeper for a knowledge assignment. It basically adds some functionality to the regular label and then gets instantiated in the form1.cs part.
public partial class Cell : System.Windows.Forms.Label
{
private bool hasBomb;
private bool isRevealed;
private int neighbourBombCount;
static int BombAmount;
// Properties
public bool HasBomb
{
get { return hasBomb; }
set { hasBomb = value; }
}
public bool IsRevealed
{
get { return isRevealed; }
set { isRevealed = value; }
}
public int NeighbourBombCount
{
get { return neighbourBombCount; }
set { neighbourBombCount = value; }
}
// constructors
public Cell()
{
hasBomb = false;
isRevealed = false;
neighbourBombCount = 0;
this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.Size = new System.Drawing.Size(50, 50);
}
and then theres the form1.cs:
public partial class Form1 : Form
{
// Public variable declarations
int chance;
Random rand1 = new Random();
static int bombAmount;
public Form1()
{
InitializeComponent();
this.AutoSize = false;
this.Width = 420;
this.Height = 420;
createGrid();
}
public void createGrid()
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
grid[i][j] = new Cell();
grid[i][j].Name = "grid" + i.ToString() + j.ToString();
grid[i][j].Location = new System.Drawing.Point(i * 49, j * 49);
grid[i][j].Size = new System.Drawing.Size(50, 50);
grid[i][j].TabIndex = 0;
chance = rand1.Next(0, 6);
if (chance % 6 == 0 && bombAmount < 10)
{
grid[i][j].HasBomb = true;
bombAmount++;
}
}
}
for (int i = 0; i < 8; i++)
{
for (int j = 0; j <8; j++)
{
this.Controls.Add(grid[i][j]);
}
}
}
private Cell[][] grid = new Cell[8][];
which has some more logic beneath which is unimportant for now. The problem is that nothing is showing up, what am I missing?
You aren't initializing the second part of your jagged array.
Try adding this:
public void createGrid() {
for (int i = 0; i < 8; i++) {
grid[i] = new Cell[8];

I need help on using an array made in one class in a different class and get its sum

In my Inputs class I have an array named score. I need to use it in my MathFun class and get the sum of it.
class Inputs
{
int amountgames;
public void AmountOfGames()
{
Console.WriteLine("How many games did you play?");
amountgames = int.Parse(Console.ReadLine());
}
public void Scores()
{
int[] score = new int[amountgames];
Console.WriteLine("score for game ");
for (int i = 0; i < score.Length; i++)
{
score[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("\nThe scores you entered are");
for (int j = 0; j < score.Length; j++)
{
Console.WriteLine(score[j]);
}
}
}
class MathFun
{
int number1;
int number2;
int total;
int averaged;
public int Average;
public int Added1;
public MathFun()
{
}
public void DivideThem()
{
Average = number1 / number2;
}
public void Added()
{
Added1 = inputs.score.sum();
//This is where in the array and its sum
}
public MathFun(int innumber1, int innumber2)
{
number1 = innumber1;
number2 = innumber2;
}
public int Number1
{
get
{
return number1;
}
set
{
number1 = value;
}
}
public int Number2
{
get
{
return number2;
}
set
{
number2 = value;
}
}
public int Total
{
get
{
return total;
}
}
public int Averaged
{
get
{
return averaged;
}
}
public void CalcTotal()
{
total = Added1;
averaged = Average;
}
}
You have two choices
Create an instance of Inputs that you can use in MathFun.
Make Scores() static, so that an instance is not required. If you do that, amountgames and AmountOfGames() will also have to become static.
Either way, you will have to return the inputs from Scores() or store them in some way in the class.
public int[] Scores()
{
int[] score = new int[amountgames];
Console.WriteLine("score for game ");
for (int i = 0; i < score.Length; i++)
{
score[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("\nThe scores you entered are");
for (int j = 0; j < score.Length; j++)
{
Console.WriteLine(score[j]);
}
}
return score;
}
Here's how you could approach it with the first approach
Inputs inputs = new Inputs();
int[] scores = Scores();
// Use scores with MathFun
NOTE: I would not generally create a function that is both responsible for writing scores out to the console and returning them. A single responsibility per method is preferred. The solution here is one that modifies your current code as little as possible.
Found my own solution
int sum = 0;
for (int i = 0; i < score.Length; i++)
{
sum += score[i];
}
add this to the array to add it all up
then just make an instance of sum

How many swaping & comparsions in each sorting algorithm?

class Sort
{
int[] arr;
int counter=0;
//Constructor
public Sort()
{
arr = new int[10000];
}
string address;
public void SwitchCase(int Case)
{
switch (Case)
{
case 1:
address = #"C:\Users\Aqib Saeed\Desktop\case1.txt";
break;
case 2:
address = #"C:\Users\Aqib Saeed\Desktop\case2.txt";
break;
case 3:
address = #"C:\Users\Aqib Saeed\Desktop\case3.txt";
break;
default:
break;
}
}
//Read file for input
public void FillArray()
{
using (StreamReader rdr = new StreamReader(address))
{
for (int i = 0; i < arr.Length; i++)
{
arr[i] = Convert.ToInt32(rdr.ReadLine());
}
}
}
// Insertion Sort
public void InsertionSort()
{
int insert;
for (int i = 1; i < arr.Length; i++)
{
insert = arr[i];
int moveItem = i;
while (moveItem > 0 && arr[moveItem - 1] > insert)
{
arr[moveItem] = arr[moveItem - 1];
moveItem--;
counter++;
}
arr[moveItem] = insert;
}
}
public void Counter()
{
Console.WriteLine(counter);
}
//Bubble Sorting
public void BubbleSort()
{
int temp;
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr.Length - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
counter++;
}
}
}
}
//Selection Sorting
public void SelectionSort()
{
int min, temp;
for (int i = 0; i < arr.Length; i++)
{
min = i;
for (int j = i + 1; j < arr.Length; j++)
if (arr[j] < arr[min])
min = j;
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
counter++;
}
}
// Write Output to file
public void Writer()
{
using (StreamWriter wrtr = new StreamWriter(#"C:\Users\AqibSaeed\Desktop\SortedOutput.txt"))
{
for (int i = 0; i < arr.Length; i++)
{
wrtr.WriteLine(arr[i]);
}
}
}
}
static void Main(string[] args)
{
Sort srt = new Sort();
Console.WriteLine("Enter Case 1 OR 2 OR 3");
srt.SwitchCase(Convert.ToInt32(Console.ReadLine()));
srt.FillArray();
srt.BubbleSort();
srt.Writer();
Console.WriteLine("Sorted Output File Is Ready");
srt.Counter();
Console.ReadLine();
}
I implement my Sort class for sorting integers and place int counter to determine number of swaps and comparsions. But I am not sure it is working correctly! Is there any other way to determine number of swaping and comparsions?
You could create a class which implements IComparable to count the comparator access and a specialized collection which counts the swaps. Like that you dont have to count the access inside of the sort algorithms and you delegate the tasks more strict to code parts.
In the index operator you count the swap operations and in the IComparable implementation you count the comparisons
Example for a class SortItem which implements the IComparable:
public class SortItem<T> : IComparable<T> where T : IComparable
{
private static int _ComparisonCount = 0;
public static int ComparisonCount
{
private set
{
_ComparisonCount = value;
}
get
{
return _ComparisonCount;
}
}
public T Value
{
get;
set;
}
public static void ResetComparisonCount()
{
_ComparisonCount = 0;
}
#region IComparable<T> Members
public int CompareTo(T other)
{
ComparisonCount++;
return this.Value.CompareTo(other);
}
#endregion
}
and the sorting collection:
public class SortCollection<T> : IList<SortItem<T>>
{
public SortCollection(IList<T> sortList)
{
InnerList = sortList;
}
private IList<T> InnerList = null;
public T this[int key]
{
get
{
return InnerList[key];
}
set
{
SwapCount++;
InnerList[key] = value;
}
}
private int _SwapCount = 0;
public int SwapCount
{
private set
{
_SwapCount = value;
}
get
{
return _SwapCount;
}
}
public void ResetSwapCount()
{
_SwapCount = 0;
}
}
Here the execution:
List<Int32> baseList = new List<int>(new Int32 {6, 2, 7, 3, 1, 6, 7 });
SortCollection<Int32> sortList = new SortCollection<int>(baseList);
//do the sorting....
Console.WriteLine("Swaps: " + sortList.SwapCount.ToString());
Console.WriteLine("Comparisons: " + SortItem<Int32>.ComparisonCount.ToString());
SortItem<Int32>.ResetComparisonCount();
sortList.ResetSwapCount();
You are only counting swaps and not counting comparisons. If you want to count comparisons then you need to add an extra counter that you increment every time you pass an if comparison.

What wrong with my loop .Need to calculate a running total

I have to build some logic to write some sort of scoreboard. The idea is this:
There are many stages:
1st stage you have 2 numbers. 7 and 3=10
2nd stage you have another 2 numbers. 5 and 1 =6
After the loop has finished, the wanted result should be:
Stage 1 total score=15 (total 1st Stage + firstTry of secondStage)
Stage 2 total score=21 (total 1st Stage + (firstTry + SecondTry of SecondStage)
What's wrong with my loop? I dont seem to get the wanted resoult.
private void Calculate(Player player)
{
for (int i = 0; i < player.Game.Stages.Length; i++)
{
int firstThrow = player.Game.Stages[i].FirstTry;
int secondThrow = player.Game.Stages[i].SecondTry;
int sumFirstAndSecond = firstThrow + secondThrow;
//If firstTry + SecondTry==10 is spare
if ((sumFirstAndSecond == 10) && (firstThrow != 10) && i != player.Game.Stages.Length- 1)
{
int stageScore= player.Game.Stages[i].TotalScore +
player.Game.Stages[i + 1].FirstTry;
player.Game.Stages[i].TotalScore = stageScore;
}
}
}
public class Stage
{
public int FirstTry { get; set; }
public int SecondTry { get; set; }
public int TotalScore { get; set; }
}
public class Player
{
public Player(string name)
{
Name = name;
Game = new Game(name);
}
public Game Game { get; set; }
public string Name { get; set; }
}
public class Game
{
public Game(string playerName)
{
PlayerName = playerName;
Stages = new Stage[10];
for (int i = 0; i < Stages.Length; i++)
{
Stages[i] = new Stage();
}
}
public Stage[] Stages { get; internal set; }
public string PlayerName { get; set; }
}
Change this:
private void Calculate(Player player)
{
for (int i = 0; i < player.Game.Stages.Length; i++)
{
int firstThrow = player.Game.Stages[i].FirstTry;
int secondThrow = player.Game.Stages[i].SecondTry;
int sumFirstAndSecond = firstThrow + secondThrow;
if ((sumFirstAndSecond == 10) && (firstThrow != 10) && i != player.Game.Stages.Length- 1)
{
int stageScore= player.Game.Stages[i].TotalScore + player.Game.Stages[i + 1].FirstTry;
player.Game.Stages[i].TotalScore = sumFirstAndSecond + stageScore;
}
else if (i > 0) player.Game.Stages[i].TotalScore = player.Game.Stages[i - 1].TotalScore + sumFirstAndSecond;
}
}
Bowling?
Try this, and do not forget to add misses (as 0).
Should work for both running and final scoring.
// All balls, including misses (0)!
public readonly IList<int> _balls = new List<int>();
private int _currentBall;
public int CalculateTotalScore()
{
int score = 0;
_currentBall = 0;
for (var frame = 0; frame < 10; frame++)
{
if (_currentBall >= _balls.Count)
break;
if (_balls[_currentBall] == 10)
{
// Strrrike!
score += AggregateScoreFromCurrentBall(3);
_currentBall++;
}
else if (AggregateScoreFromCurrentBall(2) == 10)
{
// Spare
score += AggregateScoreFromCurrentBall(3);
_currentBall += 2;
}
else
{
score += AggregateScoreFromCurrentBall(2);
_currentBall += 2;
}
}
return score;
}
private int AggregateScoreFromCurrentBall(int numberOfBallsToSum)
{
var sum = 0;
for (var i = 0; i < numberOfBallsToSum; i++)
if (_currentBall + i < _balls.Count)
sum += _balls[_currentBall + i];
return sum;
}

Categories

Resources