Vienna
8일차 본문
1. 실습_ArraySample
using System;
namespace _10장_ArraySample_359page
{
class Program
{
static void Main(string[] args)
{
int[] scores = new int[5];
scores[0] = 80;
scores[1] = 74;
scores[2] = 81;
scores[3] = 90;
scores[4] = 34;
foreach (int score in scores)
Console.WriteLine(score);
int sum = 0;
foreach (int score in scores)
sum += score;
int avg = sum / scores.Length;
Console.WriteLine($"Average Score: {avg}");
}
}
}
2. 실습_ArraySample2
using System;
namespace _10장_ArraySample2_361page
{
class Program
{
static void Main(string[] args)
{
int[] scores = new int[5];
scores[0] = 80;
scores[1] = 74;
scores[2] = 81;
scores[^2] = 90;
scores[^1] = 34;
foreach (int score in scores)
Console.WriteLine(score);
int sum = 0;
foreach (int score in scores)
sum += score;
int avg = sum / scores.Length;
Console.WriteLine($"Average Score: {avg}");
}
}
}
3. 실습_IntializingArray
using System;
namespace _10장_IntializingArray_363page
{
class Program
{
static void Main(string[] args)
{
string[] array1 = new string[3] { "안녕", "Hello", "Halo" };
Console.WriteLine("array1...");
foreach (string greeting in array1)
Console.WriteLine($" {greeting}");
string[] array2=new string[] { "안녕", "Hello", "Halo" };
Console.WriteLine("\narray2...");
foreach (string greeting in array2)
Console.WriteLine($" {greeting}");
string[] array3 = { "안녕", "Hello", "Halo" };
Console.WriteLine("\narray3...");
foreach (string greeting in array3)
Console.WriteLine($" {greeting}");
}
}
}
4. 실습_DerivedFromArray
using System;
namespace _10장_DerivedFromArray_365page
{
class Program
{
static void Main(string[] args)
{
int[] array = new int[] { 10, 30, 20, 7, 1 };
Console.WriteLine($"Type Of array: {array.GetType()}");
Console.WriteLine($"Base type Of array: {array.GetType().BaseType}");
}
}
}
5. 실습_MoreOnArray
using System;
namespace _10장_MoreOnArray_366page
{
class Program
{
private static bool CheckPassed(int score)
{ return score >= 60; }
private static void Print(int value)
{ Console.Write($"{value} "); }
static void Main(string[] args)
{
int[] scores = new int[] { 80, 74, 81, 90, 34 };
foreach (int score in scores)
Console.Write($"{score} ");
Console.WriteLine();
Array.Sort(scores);
Array.ForEach<int>(scores, new Action<int>(Print));
Console.WriteLine();
Console.WriteLine($"Number of dimensions: {scores.Rank}");
Console.WriteLine($"Binary Search: 81 is at " + $"{Array.BinarySearch<int>(scores, 81)}");
Console.WriteLine($"Linear Search: 81 is at " + $"{Array.IndexOf(scores, 90)}");
Console.WriteLine($"Everyone passed ? : " + $"{Array.TrueForAll<int>(scores, CheckPassed)}");
int index = Array.FindIndex<int>(scores, (score) => score < 60);
scores[index] = 61;
Console.WriteLine($"Everyone passed ? : " + $"{Array.TrueForAll<int>(scores, CheckPassed)}");
Console.WriteLine("Old length of scores: " + $"{scores.GetLength(0)}");
Array.Resize<int>(ref scores, 10);
Console.WriteLine($"New length of scores: " + $"{scores.Length}");
Array.ForEach<int>(scores, new Action<int>(Print));
Console.WriteLine();
Array.Clear(scores, 3, 7);
Array.ForEach<int>(scores, new Action<int>(Print));
Console.WriteLine();
int[] sliced = new int[3];
Array.Copy(scores, 0, sliced, 0, 3);
Array.ForEach<int>(sliced, new Action<int>(Print));
Console.WriteLine();
}
}
}
6. 실습_Slice
using System;
namespace _10장_Slice_371page
{
class Program
{
static void PrintArray(System.Array array)
{
foreach (var e in array)
Console.Write(e);
Console.WriteLine();
}
static void Main(string[] args)
{
char[] array = new char['Z' - 'A' + 1];
for (int i = 0; i < array.Length; i++)
array[i] = (char)('A' + i);
PrintArray(array[..]);
PrintArray(array[5..]);
Range range_5_10 = 5..10;
PrintArray(array[range_5_10]);
Index last = ^0;
Range range_5_last = 5..last;
PrintArray(array[range_5_last]);
PrintArray(array[^4..^1]);
}
}
}
7. 실습_2DArray
using System;
namespace _10장_2DArray_374page
{
class Program
{
static void Main(string[] args)
{
int[,] arr = new int[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };
for(int i=0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
Console.Write($"[{i}, {j}]: {arr[i, j]} ");
Console.WriteLine();
}
Console.WriteLine();
int[,] arr2 = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
for (int i = 0; i < arr2.GetLength(0); i++)
{
for (int j = 0; j < arr2.GetLength(1); j++)
Console.Write($"[{i}, {j}]: {arr2[i, j]} ");
Console.WriteLine();
}
Console.WriteLine();
int[,] arr3 = { { 1, 2, 3 }, { 4, 5, 6 } };
for (int i = 0; i < arr3.GetLength(0); i++)
{
for (int j = 0; j < arr3.GetLength(1); j++)
Console.Write($"[{i}, {j}]: {arr3[i, j]} ");
Console.WriteLine();
}
Console.WriteLine();
}
}
}
8. 실습_3DArray
using System;
namespace _10장_3DArray_376page
{
class Program
{
static void Main(string[] args)
{
int[,,] array = new int[4, 3, 2]
{
{{ 1,2}, { 3,4},{ 5,6} },
{{ 1,4}, { 2,5},{ 3,6} },
{{ 6,5}, { 4,3},{ 2,1} },
{{ 6,3}, { 5,2},{ 4,1} }
};
for (int i=0; i<array.GetLength(0); i++)
{
for(int j=0; j<array.GetLength(1); j++)
{
Console.Write("{ ");
for (int k = 0; k < array.GetLength(2); k++)
Console.Write($"{array[i, j, k]} ");
Console.Write("} ");
}
Console.WriteLine();
}
}
}
}
9. 실습_JaggedArray
using System;
namespace _10장_JaggedArray_379page
{
class Program
{
static void Main(string[] args)
{
int[][] jagged = new int[3][];
jagged[0] = new int[5] { 1, 2, 3, 4, 5 };
jagged[1] = new int[] { 10, 20, 30 };
jagged[2] = new int[] { 100, 200 };
foreach(int[] arr in jagged)
{
Console.Write($"Length: {arr.Length}, ");
foreach (int e in arr)
{
Console.Write($"{e} ");
}
Console.WriteLine("");
}
Console.WriteLine("");
int[][] jagged2 = new int[2][]
{
new int[] { 1000,2000},
new int[4] { 6,7,8,9}
};
foreach (int[] arr in jagged2)
{
Console.Write($"Length: {arr.Length}, ");
foreach (int e in arr)
{
Console.Write($"{e} ");
}
Console.WriteLine("");
}
Console.WriteLine("");
}
}
}
10. 실습_UsingList
using System;
using System.Collections;
namespace _10장_UsingList_382page
{
class Program
{
static void Main(string[] args)
{
ArrayList list = new ArrayList();
for (int i = 0; i < 5; i++)
list.Add(i);
foreach (object obj in list)
Console.Write($"{obj} ");
Console.WriteLine();
list.RemoveAt(2);
foreach (object obj in list)
Console.Write($"{obj} ");
Console.WriteLine();
list.Insert(2, 2);
foreach (object obj in list)
Console.Write($"{obj} ");
Console.WriteLine();
list.Add("abc");
list.Add("def");
foreach (object obj in list)
Console.Write($"{obj} ");
Console.WriteLine();
}
}
}
11. 실습_UsingQueue
using System;
using System.Collections;
namespace _10장_UsingQueue_385page
{
class Program
{
static void Main(string[] args)
{
Queue que = new Queue();
que.Enqueue(1);
que.Enqueue(2);
que.Enqueue(3);
que.Enqueue(4);
que.Enqueue(5);
while (que.Count > 0)
Console.WriteLine(que.Dequeue());
}
}
}
진짜 간편하네...
12. 실습_UsingStack
using System;
using System.Collections;
namespace _10장_UsingStack_378page
{
class Program
{
static void Main(string[] args)
{
Stack stack = new Stack();
stack.Push(1);
stack.Push(2);
stack.Push(3);
stack.Push(4);
stack.Push(5);
while (stack.Count > 0)
Console.WriteLine(stack.Pop());
}
}
}
13. 실습_UsingHashtable
using System;
using System.Collections;
namespace _10장_UsingHashtable_388page
{
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht["하나"] = "one";
ht["둘"] = "two";
ht["셋"] = "three";
ht["넷"] = "four";
ht["다섯"] = "five";
Console.WriteLine(ht["하나"]);
Console.WriteLine(ht["둘"]);
Console.WriteLine(ht["셋"]);
Console.WriteLine(ht["넷"]);
Console.WriteLine(ht["다섯"]);
}
}
}
14. 실습_InitializingCollections
using System;
using System.Collections;
using static System.Console;
namespace _10장_InitializingCollections_390page
{
class Program
{
static void Main(string[] args)
{
int[] arr = { 123, 456, 789 };
ArrayList list = new ArrayList(arr);
foreach (object item in list)
WriteLine($"ArrayList: {item}");
WriteLine();
Stack stack = new Stack(arr);
foreach (object item in stack)
WriteLine($"Stack: {item}");
WriteLine();
Queue queue = new Queue(arr);
foreach (object item in queue)
WriteLine($"Queue: {item}");
WriteLine();
ArrayList list2 = new ArrayList() { 11, 22, 33 };
foreach (object item in list2)
WriteLine($"ArrayList2: {item}");
WriteLine();
}
}
}
15. 실습_Indexer
using System;
using System.Collections;
namespace _10장_Indexer_394page
{
class MyList
{
private int[] array;
public MyList()
{
array = new int[3];
}
public int this[int index]
{
get { return array[index]; }
set
{
if (index >= array.Length)
{
Array.Resize<int>(ref array, index + 1);
Console.WriteLine($"Array Resized: {array.Length}");
}
array[index] = value;
}
}
public int Length
{
get { return array.Length; }
}
}
class Program
{
static void Main(string[] args)
{
MyList list = new MyList();
for (int i = 0; i < 5; i++)
list[i] = i;
for (int i = 0; i < 5; i++)
Console.WriteLine(list[i]);
}
}
}
16. 실습_Yield
using System;
using System.Collections;
namespace _10장_Yield_396page
{
class MyEnumerator
{
int[] numbers = { 1, 2, 3, 4 };
public IEnumerator GetEnumerator()
{
yield return numbers[0];
yield return numbers[1];
yield return numbers[2];
yield break;
}
}
class Program
{
static void Main(string[] args)
{
var obj = new MyEnumerator();
foreach (int i in obj)
Console.WriteLine(i);
}
}
}
17. 실습_Enumerable
using System;
using System.Collections;
namespace _10장_Enumerable_398page
{
class MyList : IEnumerable, IEnumerator
{
private int[] array;
int position = -1;
public MyList()
{
array = new int[3];
}
public int this[int index]
{
get { return array[index]; }
set
{
if (index >= array.Length)
{
Array.Resize<int>(ref array, index + 1);
Console.WriteLine($"Array Resized: {array.Length}");
}
array[index] = value;
}
}
public object Current
{
get { return array[position]; }
}
public bool MoveNext()
{
if (position == array.Length - 1)
{
Reset();
return false;
}
position++;
return (position < array.Length);
}
public void Reset()
{
position = -1;
}
public IEnumerator GetEnumerator()
{
return this;
}
}
class Program
{
static void Main(string[] args)
{
MyList list = new MyList();
for (int i = 0; i < 5; i++)
list[i] = i;
foreach (int e in list)
Console.WriteLine(e);
}
}
}
18. 연습문제2
다음 두 행렬 A와 B의 곱을 2차원 배열을 이용하여 계산하는 프로그램을 작성하세요.
using System;
namespace 연습문제2_401page
{
class Program
{
static void Main(string[] args)
{
int[,] arrA = new int[2, 2] { { 3, 2 }, { 1, 4 } };
int[,] arrB = new int[2, 2] { { 9, 2 }, { 1, 7 } };
int[,] result = new int[2, 2];
for (int i = 0; i < result.GetLength(0); i++)
{
for (int j = 0; j < result.GetLength(1); j++)
{
result[i, j] = arrA[i, 0] * arrB[0, j] + arrA[i, 1] * arrB[1, j];
}
}
for (int i = 0; i < result.GetLength(0); i++)
{
for (int j = 0; j < result.GetLength(1); j++)
Console.Write($"{result[i, j]} ");
Console.WriteLine();
}
}
}
}
이렇게 작성하는 게 맞는 것인가... 답은 제대로 나오는데 0과 1을 그대로 넣었더니 하드코딩을 한 기분이다.
그래서 검색을 해봤더니 C#은 아니지만 C언어로 풀이한 게 나왔다.
void multiply(result r, matrix1 a, matrix2 b) {
int i, j, k;
for (i=0; i < ROWS; i++) {
for (j=0; j < ROWS; j++) {
for (k=0; k < COLS; k++) {
r[i][j] += a[i][k] * b[k][j];
}
}
}
}
문제를 풀 때에도 하나의 for문을 더 넣어야 할 것 같다고 생각이 들었는데 역시나였다. 그런데 그렇게 되면 너무 복잡해 보일 것 같기도 해서 그냥 직접 입력을 했다... 하지만 생각해보면 길이가 2가 아니라 3이상으로 넘어갔을 경우에는 그렇게 비효율적일 수가 없다. 역시 for 문을 하나 더 입력해서 작성하는 쪽이 나을 것 같단 생각이 들었다.
19. 연습문제5
다음과 같은 결과를 출력하도록 아래의 코드를 완성하세요.
회사: Microsoft
URL: www.microsoft.com
using System;
using System.Collections;
namespace 연습문제5_401page
{
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht["회사"] = "Microsoft";
ht["URL"] = "www.microsoft.com";
Console.WriteLine("회사: {0}", ht["회사"]);
Console.WriteLine("URL: {0}", ht["URL"]);
}
}
}
Comments