I'm new in C#. I have this program and I need to add the function for insert, function min, function max, and function display.
namespace unSortedArrayAssignment
{
class unSortedArray
{
public int size;
public int[] array;
//Constructor for an empty unsorted array
public unSortedArray(int MAX_SIZE)
{
array = new int[MAX_SIZE]; //Create a C# array of size MAX_SIZE
size = 0; // Set size of unSortedArray to 0
}
//Append assuming array is not full
public void Append(int value)
{
array[size] = value;
size++;
}
//Remove the last item
public void Remove()
{
if (size != 0)
size--;
}
//Search for an item
public int Search(int value)
{
for (int counter = 0; counter < size; counter++)
{
if (array[counter] == value)
return counter;
}
return -1;
}
//Delete an item
public void Delete(int value)
{
int index = Search(value);
if (index != 0)
{
for (int counter = index; counter < size; counter++)
array[counter] = array[counter + 1];
size--;
}
}
}
}
class unSortedArray
{
public int size;
public int[] array;
public unSortedArray()
{
array = new int[int size here];
}
public int Min()
{
return array.Min();
}
public int Max()
{
return array.Max();
}
public void Insert(int value)
{
Array.Resize<int>(ref array, array.Count() + 1);
array[array.Count() - 1] = value;
}
}
Related
public class Vector < T>
{
private const int DEFAULT_CAPACITY = 10;
private T[] data;
public int Count { get; private set; } = 0;
public int Capacity
{
get { return data.Length; }
}
public Vector(int capacity)
{
data = new T[capacity];
}
public Vector() : this(DEFAULT_CAPACITY) { }
public T this[int index]
{
get
{
if (index >= Count || index < 0) throw new IndexOutOfRangeException();
return data[index];
}
set
{
if (index >= Count || index < 0) throw new IndexOutOfRangeException();
data[index] = value;
}
}
private void ExtendData(int extraCapacity)
{
T[] newData = new T[Capacity + extraCapacity];
for (int i = 0; i < Count; i++) newData[i] = data[i];
data = newData;
}
public void Add(T element)
{
if (Count == Capacity) ExtendData(DEFAULT_CAPACITY);
data[Count++] = element;
}
public int IndexOf(T element)
{
for (var i = 0; i < Count; i++)
{
if (data[i].Equals(element)) return i;
}
return -1;
}
public void Insert(int index, T element)
{
if (Count == Capacity)
{
ExtendData(DEFAULT_CAPACITY);
}
if (index >= Count || index < 0)
throw new IndexOutOfRangeException();
int tmp = Count;
while (tmp != index)
{
//shuffle
data[tmp] = data[tmp - 1];
tmp--;
}
data[tmp] = element;
Count++;
}
I am working with arrays and vectors. Just wondering how could we create a function which displays all elements in a vector. I am confused because of the data scope. I can write a function for a simple array but how do you do that when you have whole class?
How do i create a function that prints all the elements stored in this vector?
I Wrote a class which allows users to set a bottom bound of array, in instance "myArray(-5, 10)" where -5 start index and 10 length of array. But I am getting an error when I compare i <= myArray.GetArrayLength. What I did wrong. I will appriciated any help.
using System;
namespace UsArrClass
{
class Program
{
class UserArr
{
private int[] _UsArr;
private int _start;
private int _len;
public int[] UsArr
{
get => this._UsArr;
set => this._UsArr = value;
}
public int BotomBoundary
{
get => this._start;
set => this._start = value;
}
public int TopBoundary => (GetUserArrLength -1) + BotomBoundary;
public int GetUserArrLength => _len;
public UserArr(int start, int len)
{
this.BotomBoundary = start;
this._len = len;
UsArr = new int [len];
}
public int this[int n]
{
get => UsArr[n - BotomBoundary];
set => UsArr[n - BotomBoundary] = value;
}
static void Main(string[] args)
{
UserArr myarr = new UserArr( 0, 3);
for (int i = myarr.BotomBoundary; i <= myarr.GetUserArrLength; i++)
{
myarr[i] = i;
Console.Write(" "+ myarr[i]);
}
Console.WriteLine();
Console.WriteLine(myarr.TopBoundary);
Console.WriteLine(myarr[1]);
Console.WriteLine(myarr.BotomBoundary);
Console.WriteLine(myarr.GetUserArrLength);
}
}
}
}
i have a c# class
public class treeItem
{
public string parentName { get; set; }
public int index { get; set; }
public List<treeItem> children { get; set; }
public treeItem()
{
children = new List<treeItem>();
}
}
i can fill it and sort it by index but i have a problem in search of index in 3rd or n level
function to add index
void AddIndexToTree(List<treeItem> children)
{
for(int i = 0; i < children.Count; i++)
{
count++;
children[i].index = count;
if (children[i].children.Count > 0)
{
AddIndexToTree(children[i].children);
}
}
}
i try to create a search function but have a problem in n level that i remove item from list so i send a copy of list to function but in n level it delete from the original list
treeItem getParentNode(int index, List<treeItem> searchList)
{
if (searchList.Count == 1)
{
if (searchList[0].index == index)
{
return searchList[0];
}
else if (searchList[0].children.Count > 0)
{
for (int i = 0; i < searchList[0].children.Count; i++ )
{
if (searchList[0].children[i].index == index)
return searchList[0].children[i];
}
List<treeItem> tempList = searchList[0].children;
return getParentNode(index, tempList);
}
}
else
{
int length = searchList.Count;
int mid;
if( length % 2 == 0)
{
mid = length / 2;
if (length != 2)
mid--;
}
else
{
mid = length / 2;
}
if (searchList[mid].index == index)
return searchList[mid];
if(searchList[mid].index > index)
{
searchList.RemoveRange(mid, searchList.Count - mid );
return getParentNode(index, searchList);
}
else
{
if (searchList.Count > 2 && searchList[mid + 1].index < index )
searchList.RemoveRange(0, mid + 1);
else
searchList.RemoveRange(0, mid);
return getParentNode(index, searchList);
}
}
return null;
}
any help in my code or another algorithm please ?
Here is an example of a simple recursive search for a specific index in a tree made up from your class: (of course, this should be a method in your class)
public treeItem Find(int index)
{
if(this.Index == index)
return this;
foreach(var child in this.children)
return child.Find(index);
return null; // Index was not found in the current treeItem or any of it's children.
}
Please note that if the treeItems in your children property are ordered by index, you can use a binary search (which is what I think you tried to do).
Protobuf doesn't support multi-dim arrays so I decided to use this implementation to make a 1D array out of a 2D one.
I get a Cannot cast from source type to destination type in the ToProtoArray method when I call the MultiLoop function. Any ideas on how to fix this?
public static ProtoArray<T> ToProtoArray<T>(this System.Array array)
{
// Copy dimensions (to be used for reconstruction).
var dims = new int[array.Rank];
for (int i = 0; i < array.Rank; i++) dims[i] = array.GetLength(i);
// Copy the underlying data.
var data = new T[array.Length];
var k = 0;
array.MultiLoop(indices => data[k++] = (T)array.GetValue(indices));
// ^^^^^^^^^^ cannot cast from source type to destination type
return new ProtoArray<T> { Dimensions = dims, Data = data };
}
public static System.Array ToArray<T>(this ProtoArray<T> protoArray)
{
// Initialize array dynamically.
var result = System.Array.CreateInstance(typeof(T), protoArray.Dimensions);
// Copy the underlying data.
var k = 0;
result.MultiLoop(indices => result.SetValue(protoArray.Data[k++], indices));
return result;
}
public static void MultiLoop(this System.Array array, System.Action<int[]> action)
{
array.RecursiveLoop(0, new int[array.Rank], action);
}
private static void RecursiveLoop(this System.Array array, int level, int[] indices, System.Action<int[]> action)
{
if (level == array.Rank)
{
action(indices);
}
else
{
for (indices[level] = 0; indices[level] < array.GetLength(level); indices[level]++)
{
RecursiveLoop(array, level + 1, indices, action);
}
}
}
[ProtoContract]
public class ProtoArray<T>
{
[ProtoMember(1)]
public int[] Dimensions { get; set; }
[ProtoMember(2)]
public T[] Data { get; set; }
}
Here's how I use this to serialize a 2D array:
[ProtoContract]
public class Tile
{
[ProtoMember(1)]
public int x;
[ProtoMember(2)]
public int y;
// ...
}
Tile[,] map; // meanwhile I assign the data to the array
map1d = Extensions.ToProtoArray<Tile[,]>(map);
using (var file = File.Create(path))
{
Serializer.Serialize(file, map1d);
}
I think this is what you need:
public class ProtoArray<T>
{
public ProtoArray(T[] array)
{
this.Data=array;
this.Dimensions=new int[array.Length];
}
public ProtoArray(T[,] array)
{
int n = array.GetLength(0);
int m = array.GetLength(1);
this.Data=new T[n*m];
for(int i = 0; i<n; i++)
{
for(int j = 0; j<m; j++)
{
// Row Major
Data[i*m+j]=array[i, j];
// For Column Major use Data[i+j*n]=array[i, j];
}
}
this.Dimensions=new[] { n, m };
}
public int[] Dimensions { get; set; }
public T[] Data { get; set; }
public T[] ToArray()
{
if(Dimensions.Length==1)
{
return Data.Clone() as T[];
}
else
{
throw new NotSupportedException();
}
}
public T[,] ToArray2()
{
if(Dimensions.Length==2)
{
int n = Dimensions[0], m = Dimensions[1];
T[,] array = new T[n, m];
for(int i = 0; i<n; i++)
{
for(int j = 0; j<m; j++)
{
array[i, j]=Data[i*m+j];
}
}
return array;
}
else
{
throw new NotSupportedException();
}
}
}
public class Tile
{
public int x;
public int y;
// ...
}
class Program
{
static void Main(string[] args)
{
Tile[,] map = new Tile[16, 4];
ProtoArray<Tile> array = new ProtoArray<Tile>(map);
//serialize array
//
// de-serialize array
Tile[,] serialized_map = array.ToArray2();
}
}
I am working on a problem regarding 2D Arrays in Excel: You are able to remove rows if a single column contains duplicate values. How can I accomplish the same thing in C#?
Please see this for reference. It removes only if a whole row contains duplicate values. I need the same thing except that only if a single column contains duplicates, that row should be removed.
Link:
Delete duplicate rows from two dimentsional array
public static class MyExtensions
{
public static IEnumerable<List<T>> ToEnumerableOfEnumerable<T>(this T[,] array)
{
int rowCount = array.GetLength(0);
int columnCount = array.GetLength(1);
for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
{
var row = new List<T>();
for (int columnIndex = 0; columnIndex < columnCount; columnIndex++)
{
row.Add(array[rowIndex, columnIndex]);
}
yield return row;
}
}
public static T[,] ToTwoDimensionalArray<T>(this List<List<T>> tuples)
{
var list = tuples.ToList();
T[,] array = null;
for (int rowIndex = 0; rowIndex < list.Count; rowIndex++)
{
var row = list[rowIndex];
if (array == null)
{
array = new T[list.Count, row.Count];
}
for (int columnIndex = 0; columnIndex < row.Count; columnIndex++)
{
array[rowIndex, columnIndex] = row[columnIndex];
}
}
return array;
}
}
public class ListEqualityComparer<T> : IEqualityComparer<List<T>>
{
public bool Equals(List<T> x, List<T> y)
{
return x.SequenceEqual(y);
}
public int GetHashCode(List<T> obj)
{
int hash = 19;
foreach (var o in obj)
{
hash = hash * 31 + o.GetHashCode();
}
return hash;
}
}
Usage:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var array = new[,] { { 1, 2 }, { 3, 4 }, { 1, 2 }, { 7, 8 } };
array = array.ToEnumerableOfEnumerable()
.Distinct(new ListEqualityComparer<int>())
.ToList()
.ToTwoDimensionalArray();
}
}