Skip to content

Instantly share code, notes, and snippets.

@Curookie
Last active February 25, 2024 07:50
Show Gist options
  • Save Curookie/dc87861c82da5bc57789b344eb17d7e1 to your computer and use it in GitHub Desktop.
Save Curookie/dc87861c82da5bc57789b344eb17d7e1 to your computer and use it in GitHub Desktop.
C# 알고리즘
Console.WriteLine (Print) 출력
[반복문]
foreach에서 마지막 원소 체크하는 법
foreach (Object element in elements.under)
{
if (element == elements.under.Last())
{
//Print Code
}
else
{
//Do other thing here
}
}
[형변환]
int int.Parse(string);
float float.Parse(string);
int aInt = (int) aFloat;
[String]
길이 - Length;
bool System.String.Contains("문자열") - 문자열 찾기
int System.String.IndexOf("문자열") - 문자열 인덱스 찾기
글자 뒤집기
public string ReverseString(string srtVarable)
{
return new string(srtVarable.Reverse().ToArray());
}
System.Linq; 하면 두가지가능
First 첫번째
Last 마지막 글자
Clone 클래스 참조 반환
CompareTo 특정 객체와 비교
CopyTo 객체 복사
EndsWith 특정 문자열로 끝나는지를 확인
Equals 비교 연산
GetEnumerator IEnumerator 인터페이스 반환
GetHashCode 해쉬 코드 반환
GetType 형식 정보 반환
GetTypeCode TypeCode 반환
IndexOf 문자열 검색
IndexOfAny 유니코드 문자열에서 먼저 나오는 문자 반환
Insert 문자열 삽입
LastIndexOf IndexOf를 뒤에서부터 수행
LastIndexOfAny IndexOfAny를 뒤에서부터 수행
PadLeft 문자열에서 남아있는 왼쪽을 빈 공백으로 채움
PadRight 문자열에서 남아있는 오른쪽을 빈 공백으로 채움
Remove 지정 개수의 문자 제거
Replace 문자열 치환
Split 문자열 분리하여 배열로 반환
StartsWith 특정 문자로 시작하는지를 확인
Substring 문자열 추출
ToCharArray 문자 배열로 변환
ToLower 소문자로 변환
ToString 객체를 나타내는 문자열 반환
ToUpper 대문자로 변환
Trim 양쪽 공백 없앰
TrimEnd 문자열 끝 부분의 공백 없앰
TrimStart 문자열 시작 부분의
[특정 문자 지우기]
var str = "My name @is ,Wan.;'; Wan";
var charsToRemove = new string[] { "@", ",", ".", ";", "'" };
foreach (var c in charsToRemove)
{
str = str.Replace(c, string.Empty);
}
Regex.Replace("He\"ll,o Wo'r.ld", "[@,\\.\";'\\\\]", string.Empty)
https://regex101.com/ 사용해서 Regex 만드는게
[자료구조]
배열 Array
정렬 Array.Sort(Array a);
크기 Length;
배열 그대로 복사하기
static void Main(string[] args)
{
// Clone the whole array
string[] args2 = (string[]) args.Clone();
배열 프로퍼티와 함수
Property Description
IsFixedSize It is used to get a value indicating whether the Array has a fixed size or not.
IsReadOnly It is used to check that the Array is read-only or not.
IsSynchronized It is used to check that access to the Array is synchronized or not.
Length It is used to get the total number of elements in all the dimensions of the Array.
LongLength It is used to get a 64-bit integer that represents the total number of elements in all the dimensions of the Array.
Rank It is used to get the rank (number of dimensions) of the Array.
SyncRoot It is used to get an object that can be used to synchronize access to the Array.
C# Array Methods
Method Description
AsReadOnly<T>(T[]) It returns a read-only wrapper for the specified array.
BinarySearch(Array,Int32,Int32,Object) It is used to search a range of elements in a one-dimensional sorted array for a value.
BinarySearch(Array,Object) It is used to search an entire one-dimensional sorted array for a specific element.
Clear(Array,Int32,Int32) It is used to set a range of elements in an array to the default value.
Clone() It is used to create a shallow copy of the Array.
Copy(Array,Array,Int32) It is used to copy elements of an array into another array by specifying starting index.
CopyTo(Array,Int32) It copies all the elements of the current one-dimensional array to the specified one-dimensional array starting at the specified destination array index
CreateInstance(Type,Int32) It is used to create a one-dimensional Array of the specified Type and length.
Empty<T>() It is used to return an empty array.
Finalize() It is used to free resources and perform cleanup operations.
Find<T>(T[],Predicate<T>) It is used to search for an element that matches the conditions defined by the specified predicate.
IndexOf(Array,Object) It is used to search for the specified object and returns the index of its first occurrence in a one-dimensional array.
Initialize() It is used to initialize every element of the value-type Array by calling the default constructor of the value type.
Reverse(Array) It is used to reverse the sequence of the elements in the entire one-dimensional Array.
Sort(Array) It is used to sort the elements in an entire one-dimensional Array.
ToString() It is used to return a string that represents the current object.
배열에서 값을 찾을 때
int[] a = {1, 2, 3, 4, 5};
int b = Array.Find(a, fIdx => fIdx == 6);
//이러면 b 에 0값이 들어감. 못 찾으면 0 임 -1 아님
배열에서 값의 위치를 찾을 때
int b Array.IndexOf(a, 6);
//이러면 -1 이 들어감 없을 땐
리스트 List
중복 제거 Distinct();
필요 System.Collections.Generic
HashSet
Add(T) 지정된 요소를 집합에 추가합니다.
Count 집합에 포함된 요소 수를 가져옵니다.
Contains(T) HashSet<T> 개체에 지정된 요소가 포함되어 있는지 확인합니다.
Remove(T) HashSet<T> 개체에서 지정된 요소를 제거합니다.
int[,] 형식
a is a two dimensional array like a grid with a fixed amount of rows and columns.
생성자
var list = new List<int>();
list : (empty)
var listA = new List<int>() {3, 2, 1};
listA : 3, 2, 1
var list = new List<int>(listA);
listB : 3, 2, 1
var list = new List<int>(10);
list.Count : 0
list.Capacity : 10
List[index]
list : 3, 2, 1
int item = list[1];
item : 3
list : 3, 2, 1
list[1] = 4;
list : 3, 4, 1
List.Add
list : 3, 2, 1
list.Add(4);
list : 3, 2, 1, 4
List.AddRange
listA : 1, 2, 3
listB : 4, 5
listA.AddRange(listB);
listA : 1, 2, 3, 4, 5
List.Clear
list : 1, 2, 3
list.Clear();
list : (empty)
List.Contains
list : 1, 2, 3
list.Contains(1) => true
list.Contains(4) => false
List.ConvertAll
listA : 1, 2, 3
var conv = new Converter<int, decimal>(x => (decimal)(x+1));
var listB = listA.ConvertAll<decimal>(conv);
listB : 2.0, 3.0, 4.0
List.CopyTo
list : 1, 2, 3
array : 0, 0, 0, 0, 0
list.CopyTo(array);
array : 1, 2, 3, 0, 0
list : 1, 2, 3
array : 0, 0, 0, 0, 0
list.CopyTo(array, arrayIndex: 2);
array : 0, 0, 1, 2, 3
list : 1, 2, 3
array : 0, 0, 0, 0, 0
list.CopyTo(index: 1, array: array, arrayIndex: 3, count: 1);
array : 0, 0, 0, 2, 0
List.Exists
list : 1, 2, 3
list.Exists(x=> x==3); => true
list.Exists(x=> x>10); => false
List.Equals (동일한 객체인지를 판단)
var listA = new List<int>() {1,2,3};
var listB = listA;
listA.Equals(listB); => true
var listA = new List<int>() {1,2,3};
var listB = new List<int>() {1,2,3};
listA.Equals(listB); => false
List.Find
list : 1, 2, 3
int item = list.Find(x => x>2);
item : 3
list : 1, 2, 3
int item = list.Find(x => x>10);
item : 0
List.FindAll
listA : 1, 2, 3
var listB = listA.FindAll(x => x>1);
listB : 2, 3
listA : 1, 2, 3
var listB = listA.FindAll(x => x>10);
listB : (empty)
List.ForEach
list : 1, 2, 3
list.ForEach(x => { Console.Write(x); });
output : 832
List.Insert
list : 1, 2, 3
list.Insert(index: 1, item: 5);
list : 1, 5, 2, 3
List.InsertRange
listA : 1, 2, 3
listB : 4, 5
listA.InsertRange(index: 1, collection: listB);
listA : 1, 4, 5, 2, 3
List.Remove
list : 1, 4, 2, 4
list.Remove(item: 4);
list: 1, 2, 4
List.RemoveAll
list : 1, 2, 3, 4
list.RemoveAll(x => x<3);
list : 3, 4
List.RemoveAt
list : 1, 2, 3, 4
list.RemoveAt(index: 2);
list : 1, 2, 4
List.RemoveRange
list : 1, 2, 3, 4, 5, 6
list.RemoveRange(index: 2, count:3)
list : 1, 2, 6
List.Reverse
list : 1, 2, 3
list.Reverse();
list : 2, 3, 1
list : 1, 2, 3
list.Reverse(index: 1, count: 2);
list : 1, 3, 2
List.Sort
list : 1, 3, 2, 4
list.Sort(); => list : 1, 2, 3, 4
list.Sort((x,y) => x.CompareTo(y)); => list : 1, 2, 3, 4
list.Sort((x,y) => y.CompareTo(x)); => list : 4, 3, 2, 1
list.Sort(new MyComparer()); => list : 1, 2, 3, 4
public class MyComparer : IComparer<int>
{
public int Compare(int x, int y) { return x.CompareTo(y); }
}
List.ToArray
list : 1, 2, 3
int[] array = list.ToArray();
array : 1, 2, 3
list : (empty)
int[] array = list.ToArray();
array : (empty)
List.TrimExcess
list : 1,2,3,4,5,
list.Count : 5
list.Capacity : 8
list.TrimExcess();
list.Count : 5
list.Capacity : 5
출처: https://tenlie10.tistory.com/155 [게임 개발 블로그]
[HashSet]
.Add<T>(e);
[Tuple]
Tuple<int, int> MyMethod()
{
// some work to find row and col
return Tuple.Create(row, col);
}
Since C# 7, you can install System.ValueTuple:
PM> Install-Package System.ValueTuple
Then you can pack and unpack a ValueTuple:
(int, int) MyMethod()
{
return (row, col);
}
(int row, int col) = MyMethod();
// mylist[row][col]
[정렬/비교]
You just need to provide an IComparer<Tuple<int, int>> or a Comparison<Tuple<int, int>>
to the List<T>.Sort method. The latter is probably easier to specify inline:
list.Sort((x, y) => y.Item1.CompareTo(x.Item1));
If you want to order by the first value and then the second value,
it becomes a bit trickier, but still feasible. For example:
list.Sort((x, y) => {
int result = y.Item1.CompareTo(x.Item1);
return result == 0 ? y.Item2.CompareTo(x.Item2) : result;
});
EDIT: I've now amended the above to sort in descending order.
Note that the right way to do this is to reverse the order of the comparison (y to x instead of x to y).
You must not just negate the return value of CompareTo - this will fail when CompareTo returns int.MinValue.
[수학]
System 에
Math.Sqrt(Double)
Math.Log(Int|Double|Float) -> 밑이 2아니라 e임
a|b Math.Min(a, b); 최소
a|b Math.Max(a, b); 최대
[순열, 조합]
```C#
static bool NextPermutation<T>(IList<T> a) where T: IComparable
{
if (a.Count < 2) return false;
var k = a.Count-2;
while (k >= 0 && a[k].CompareTo( a[k+1]) >=0) k--;
if(k<0)return false;
var l = a.Count - 1;
while (l > k && a[l].CompareTo(a[k]) <= 0) l--;
var tmp = a[k];
a[k] = a[l];
a[l] = tmp;
var i = k + 1;
var j = a.Count - 1;
while(i<j)
{
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
i++;
j--;
}
return true;
}
```
And the demo/test code:
```C#
var src = "1234".ToCharArray();
do
{
Console.WriteLine(src);
}
while (NextPermutation(src));
```
Permutations with repetition
static IEnumerable<IEnumerable<T>>
GetPermutationsWithRept<T>(IEnumerable<T> list, int length)
{
if (length == 1) return list.Select(t => new T[] { t });
return GetPermutationsWithRept(list, length - 1)
.SelectMany(t => list,
(t1, t2) => t1.Concat(new T[] { t2 }));
}
Output:
{1,1} {1,2} {1,3} {1,4} {2,1} {2,2} {2,3} {2,4} {3,1} {3,2} {3,3} {3,4} {4,1} {4,2} {4,3} {4,4}
Permutations
static IEnumerable<IEnumerable<T>>
GetPermutations<T>(IEnumerable<T> list, int length)
{
if (length == 1) return list.Select(t => new T[] { t });
return GetPermutations(list, length - 1)
.SelectMany(t => list.Where(o => !t.Contains(o)),
(t1, t2) => t1.Concat(new T[] { t2 }));
}
Output:
{1,2} {1,3} {1,4} {2,1} {2,3} {2,4} {3,1} {3,2} {3,4} {4,1} {4,2} {4,3}
K-combinations with repetition
static IEnumerable<IEnumerable<T>>
GetKCombsWithRept<T>(IEnumerable<T> list, int length) where T : IComparable
{
if (length == 1) return list.Select(t => new T[] { t });
return GetKCombsWithRept(list, length - 1)
.SelectMany(t => list.Where(o => o.CompareTo(t.Last()) >= 0),
(t1, t2) => t1.Concat(new T[] { t2 }));
}
Output:
{1,1} {1,2} {1,3} {1,4} {2,2} {2,3} {2,4} {3,3} {3,4} {4,4}
K-combinations
static IEnumerable<IEnumerable<T>>
GetKCombs<T>(IEnumerable<T> list, int length) where T : IComparable
{
if (length == 1) return list.Select(t => new T[] { t });
return GetKCombs(list, length - 1)
.SelectMany(t => list.Where(o => o.CompareTo(t.Last()) > 0),
(t1, t2) => t1.Concat(new T[] { t2 }));
}
Output:
{1,2} {1,3} {1,4} {2,3} {2,4} {3,4}
List<List<T> a = collection.Select(c => c.ToList()) // convert each collection in a list
.Tolist();
활용 예)
해커랭크 Two Charactor 문제
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;
class Solution {
static IEnumerable<IEnumerable<T>>
GetKCombs<T>(IEnumerable<T> list, int length) where T : IComparable
{
if (length == 1) return list.Select(t => new T[] { t });
return GetKCombs(list, length - 1)
.SelectMany(t => list.Where(o => o.CompareTo(t.Last()) > 0),
(t1, t2) => t1.Concat(new T[] { t2 }));
}
// Complete the alternate function below.
static int alternate(string s) {
int r = 0;
HashSet<char> chList = new HashSet<char>();
List<List<char>> chComb = new List<List<char>>();
foreach(var e in s) {
chList.Add(e);
}
chComb = GetKCombs(chList.ToList(), 2).Select(c => c.ToList()).ToList();
for(int i=0; i<chComb.Count; i++) {
bool isOk=true;
char f;
string temp = s;
string rx = "[^"+chComb[i][0].ToString()+chComb[i][1].ToString()+"]";
temp = Regex.Replace(temp, rx, string.Empty);
f = temp[0];
for(int j=1; j<temp.Length; j++) {
if(temp[j]==f) { isOk=false; break; }
else f = temp[j];
}
if(isOk) r = Math.Max(r, temp.Length);
}
return r;
}
static void Main(string[] args) {
TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
int l = Convert.ToInt32(Console.ReadLine().Trim());
string s = Console.ReadLine();
int result = alternate(s);
textWriter.WriteLine(result);
textWriter.Flush();
textWriter.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment