
int[] arr = new int[2];
int[] temp = { 3, 5, 7 };
arr = temp;
foreach(int n in arr)
{
Console.WriteLine(n);
}


동적배열의 확장
int[] arr;
public App()
{
arr = new int[2];
AddItem(3);
AddItem(5);
AddItem(7);
foreach (int n in arr)
{
Console.WriteLine(n);
}
}
void AddItem(int item)
{
int emptyIndex = -1;
for (int i = 0; i < this.arr.Length; i++)
{
if (this.arr[i] == 0)
{
emptyIndex = i;
break;
}
}
if (emptyIndex == -1)
{
int[] temp = new int[this.arr.Length + 1];
for (int i = 0; i < this.arr.Length; i++)
{
temp[i] = this.arr[i];
}
this.arr = temp;
this.arr[this.arr.Length - 1] = item;
}
else
{
this.arr[emptyIndex] = item;
}
}


동적배열의 축소
class App
{
int[] arr = { 3, 4, 5 };
public App()
{
Remove(3);
foreach (int n in arr)
{
Console.WriteLine(n);
}
}
void Remove(int number)
{
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == number)
{
arr[i] = 0;
Push();
return;
}
}
}
void Push()
{
bool check = false;
while (!check)
{
check = true;
for (int i = 0; i < arr.Length-1; i++)
{
if (arr[i] == 0)
{
arr[i] = arr[i + 1];
arr[i + 1] = 0;
check = false;
}
}
}
int[] temp = new int[arr.Length - 1];
for (int i = 0; i < temp.Length; i++)
{
temp[i] = arr[i];
}
arr = temp;
}

class Item
{
public string name;
public Item(string name)
{
this.name = name;
}
}
Item[] inven = new Item[1];
public App()
{
Console.WriteLine("inven Length: {0}", inven.Length);
AddItem("단검");
AddItem("장검");
AddItem("대검");
AddItem("창");
for (int i = 0; i < inven.Length; i++)
{
if (inven[i] != null)
{
Console.WriteLine(inven[i].name);
}
}
Console.WriteLine("inven Length: {0}",inven.Length);
}
void AddItem(string name)
{
for(int i=0; i<inven.Length; i++)
{
if (inven[i] == null)
{
inven[i] = new Item(name);
return;
}
}
AddArray(name);
}
void AddArray(string name)
{
Item[] temp = new Item[inven.Length + 1];
for(int i=0; i<inven.Length; i++)
{
temp[i] = inven[i];
}
inven = temp;
AddItem(name);
}

'C# > 수업 내용' 카테고리의 다른 글
| [C#] 재귀함수 (0) | 2021.09.16 |
|---|---|
| [C#] Linked List (연결리스트), Flowchart (순서도) (0) | 2021.09.15 |
| [C#] params, out, ref (0) | 2021.09.13 |
| [C#] thread, lock (0) | 2021.09.12 |
| [C#] Iterator, yield (0) | 2021.09.10 |