Both sides previous revisionPrevious revisionNext revision | Previous revision |
programming_tips_and_tricks [2015/09/22 10:34] – [재귀(Recursion)] ledyx | programming_tips_and_tricks [2021/02/07 03:15] (current) – external edit 127.0.0.1 |
---|
| |
= 공통 = | = 공통 = |
| |
| == 한글 자동완성 == |
| https://support.microsoft.com/ko-kr/kb/2701840 |
| |
== Polymorphism(다형성) == | == Polymorphism(다형성) == |
int sec = (int)(decimalPart2 * 60); | int sec = (int)(decimalPart2 * 60); |
| |
return string.Format("{0:D02}:{1:D02}:{2:D03}", deg, min, sec); | return string.Format("{0:D02}:{1:D02}:{2:D02}", deg, min, sec); |
} | } |
| |
{ | { |
return (double)deg + ((double)min / 60) + ((double)sec / 3600); | return (double)deg + ((double)min / 60) + ((double)sec / 3600); |
| } |
| |
| |
| |
| |
| /* 신규 추가 */ |
| |
| // <summary> |
| /// Degree → 도분초 (단위 포함) |
| /// (-122.333333 → 122:20:00 W) |
| /// </summary> |
| public static string Degree2DMS(double degree) |
| { |
| int deg = (int)Math.Abs(degree); |
| |
| double min_temp = (Math.Abs(degree) - deg) * 60; |
| double min_decPart = min_temp - (int)min_temp; |
| int min = min_decPart >= 0.999 ? (int)Math.Round(min_temp, 1, MidpointRounding.AwayFromZero) : (int)min_temp; //소숫점이 0에 수렴하는가? |
| |
| double sec_temp = (Math.Abs(degree) - deg - ((double)min / (double)60)) * 3600; |
| double sec_decPart = sec_temp - (int)sec_temp; |
| int sec = sec_decPart >= 0.999 ? (int)Math.Round(sec_temp, 1, MidpointRounding.AwayFromZero) : (int)sec_temp; //소숫점이 0에 수렴하는가? |
| |
| |
| |
| string unit = string.Empty; |
| string fmt = string.Empty; |
| if (deg <= 90) |
| { |
| fmt = "2"; |
| unit = degree >= 0 ? " N" : " S"; |
| } |
| else |
| { |
| fmt = "3"; |
| unit = degree >= 0 ? " E" : " W"; |
| } |
| |
| return string.Format("{0:D0" + fmt + "}:{1:D02}:{2:D2}", deg, min, sec) + unit; |
| } |
| |
| /// <summary> |
| /// Degree → 천분율 (단위 포함) |
| /// (-122.333333 → 122:20.660 W) |
| /// </summary> |
| /// <param name="degree"></param> |
| /// <returns></returns> |
| public static string Degree2Permil(double degree) |
| { |
| string unit = string.Empty; |
| string fmt = string.Empty; |
| |
| double absVal = Math.Abs(degree); |
| |
| if ((int)absVal <= 90) |
| { |
| fmt = "00"; |
| unit = degree >= 0 ? " N" : " S"; |
| } |
| else |
| { |
| fmt = "000"; |
| unit = degree >= 0 ? " E" : " W"; |
| } |
| |
| |
| return ((int)absVal).ToString(fmt) + ":" + ((absVal - (int)absVal) * 60).ToString("00.000") + unit; |
| } |
| |
| |
| |
| /// <summary> |
| /// 도분초 (단위포함) → Degree |
| /// (122:20:00 W → -122.333333) |
| /// </summary> |
| /// <param name="degree"></param> |
| /// <returns></returns> |
| public static double DMS2Degree(string dms) |
| { |
| int unitIndex = dms.LastIndexOf(' '); |
| string unit = dms.Substring(unitIndex + 1, 1).Trim(); |
| |
| |
| string[] dmsValue = dms.Substring(0, unitIndex).Split(':'); |
| |
| double result = double.Parse(dmsValue[0]) + (double)(double.Parse(dmsValue[1]) / (double)60) + (double)(double.Parse(dmsValue[2]) / (double)3600); |
| |
| if (unit.ToUpper().Equals("W") || unit.ToUpper().Equals("S")) |
| result = -result; |
| |
| return result; |
| } |
| |
| /// <summary> |
| /// 천분율 (단위포함) → Degree |
| /// (122:20.660 W → -122.333333) |
| /// </summary> |
| /// <param name="degree"></param> |
| /// <returns></returns> |
| public static double Permil2Degree(string permil) |
| { |
| int unitIndex = permil.LastIndexOf(' '); |
| string unit = permil.Substring(unitIndex + 1, 1).Trim(); |
| |
| |
| string permilValue = permil.Substring(0, unitIndex); |
| |
| int colonIndex = permilValue.IndexOf(':'); |
| |
| int deg = int.Parse(permilValue.Substring(0, colonIndex)); |
| double min = double.Parse(permilValue.Substring(colonIndex + 1, permilValue.Length - (colonIndex + 1))); |
| |
| |
| double result = (double)deg + min / 60; |
| |
| if (unit.ToUpper().Equals("W") || unit.ToUpper().Equals("S")) |
| result = -result; |
| |
| return result; |
} | } |
</sxh> | </sxh> |
| |
| |
=== 중심점으로부터 반지름(Radius)과 각도(Degree)를 알 때 X,Y 좌표 얻기 === | === 각도, 반지름 ↔ X, Y 좌표 === |
<sxh csharp> | <sxh csharp> |
private Point GetPoints(double radius, double degree) | public Tuple<double, double> DegreeRadius2XY(double degree, double radius) |
{ | { |
double radian = 3.1415926535897932 / (180 / degree); | double radian = Degree2Radian(degree); |
| return Tuple.Create(radius * Math.Cos(radian), radius * Math.Sin(radian)); |
| } |
| |
Point p = new Point(); | public Tuple<double, double> XY2DegreeRadius(double x, double y) |
p.X = radius * Math.Cos(radian); //x = r * cosθ | { |
p.Y = radius * Math.Sin(radian); //y = r * sinθ | double degree = Math.Atan2(y, x) * (180 / 3.1415926535897932); |
| double radious = Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2)); |
| return Tuple.Create(degree, radious); |
| } |
| |
return p; | public double Degree2Radian(double degree) |
| { |
| return 3.1415926535897932 / (180 / degree); |
} | } |
</sxh> | </sxh> |
== 정렬 알고리즘(Sort Algorithm) == | == 정렬 알고리즘(Sort Algorithm) == |
=== 합병 정렬(Merge Sort) === | === 합병 정렬(Merge Sort) === |
[[Merge Sort | 합병 정렬(Merge Sort)]] | [[algorithm:Merge Sort | 합병 정렬(Merge Sort)]] |
| |
| |
| = Language & FrameWork = |
| |
| == Java == |
| |
| === 양력/음력 날짜 계산 === |
| |
| {{:calendarlib.zip|}} |
| |
| * http://site.icu-project.org/download |
| * https://github.com/JodaOrg/joda-time/releases |
| |
=== 중복되지 않는 난수 생성 === | |
<sxh java> | <sxh java> |
//language : Java | import org.joda.time.DateTime; |
//1~5 중복되지 않는 난수 발생 | |
| import com.ibm.icu.util.ChineseCalendar; |
int[] arr = new int[5]; | |
Random random = new Random(); | public class LunarDateTime { |
| |
for(int i=0 ; i<arr.length ; i++) { | private static int yearCorrectionValue = 2637; |
arr[i] = random.nextInt(arr.length)+1; | |
| private LunarDateTime() { |
for(int j=0 ; j<i ; j++) { | } |
if(j!=i && arr[j] == arr[i]) | |
i--; | /** |
} | * |
| * @return 오늘 음력날짜 |
| */ |
| public static DateTime now() { |
| ChineseCalendar cc = new ChineseCalendar(); |
| |
| int year = cc.get(ChineseCalendar.EXTENDED_YEAR) - yearCorrectionValue; |
| int monthOfYear = cc.get(ChineseCalendar.MONTH) + 1; |
| int dayOfMonth = cc.get(ChineseCalendar.DAY_OF_MONTH); |
| |
| int[] hms = getNowHMS(); |
| return new DateTime(year, monthOfYear, dayOfMonth, hms[0], hms[1], hms[2]); |
| } |
| |
| public static DateTime solarToLunar(int solarYear, int solarMonthOfYear, int solarDayOfMonth) { |
| |
| int[] hms = getNowHMS(); |
| DateTime dt = new DateTime(solarYear, solarMonthOfYear, solarDayOfMonth, hms[0], hms[1], hms[2]); |
| |
| ChineseCalendar cc = new ChineseCalendar(); |
| cc.setTimeInMillis(dt.getMillis()); |
| |
| int year = cc.get(ChineseCalendar.EXTENDED_YEAR) - yearCorrectionValue; |
| int monthOfYear = cc.get(ChineseCalendar.MONTH) + 1; |
| int dayOfMonth = cc.get(ChineseCalendar.DAY_OF_MONTH); |
| |
| return new DateTime(year, monthOfYear, dayOfMonth, hms[0], hms[1], hms[2]); |
| } |
| |
| public static DateTime lunar2Solar(int lunarYear, int lunarMonthOfYear, int lunarDayOfMonth) { |
| ChineseCalendar cc = new ChineseCalendar(); |
| cc.set(ChineseCalendar.EXTENDED_YEAR, lunarYear + yearCorrectionValue); |
| cc.set(ChineseCalendar.MONTH, lunarMonthOfYear - 1); |
| cc.set(ChineseCalendar.DAY_OF_MONTH, lunarDayOfMonth); |
| |
| int[] hms = getNowHMS(); |
| cc.set(ChineseCalendar.HOUR_OF_DAY, hms[0]); |
| cc.set(ChineseCalendar.MINUTE, hms[0]); |
| cc.set(ChineseCalendar.SECOND, hms[0]); |
| |
| return new DateTime(cc.getTimeInMillis()); |
| } |
| |
| private static int[] getNowHMS() { |
| DateTime now = DateTime.now(); |
| return new int[] {now.getHourOfDay(), now.getMinuteOfHour(), now.getSecondOfMinute()}; |
| } |
} | } |
</sxh> | </sxh> |
| |
| |
= Java & C# = | |
| |
== C# - Lambda 이용하여 오름차순 정렬 == | |
<sxh csharp> | |
List<Point> points = new List<Points>(); | |
points.Add(new Point(11.0, 13.0)); | |
//... | |
| |
points.Sort((Point point1, Point point2) => point1.Y.CompareTo(point2.Y)); | |
</sxh> | |
| |
| |
== 포인터와 구조체 기초 개념 예제 == | == C == |
| |
| === 포인터와 구조체 기초 개념 예제 === |
<sxh c ; collapse:true> | <sxh c ; collapse:true> |
#include <stdio.h> | #include <stdio.h> |
</sxh> | </sxh> |
| |
= C = | === 동적 배열 할당 === |
| |
== 동적 배열 할당 == | |
<sxh c> | <sxh c> |
//1차원 | //1차원 |
| |
| |
= Android = | == Android == |
== Parcelable == | === Parcelable === |
* Intent를 이용하여 **Reference Type**의 데이터를 넘길 때 사용. | * Intent를 이용하여 **Reference Type**의 데이터를 넘길 때 사용. |
http://arsviator.tistory.com/169 | http://arsviator.tistory.com/169 |
| |
== Uri에서 실제 경로를 받아오는 Method == | === Image 압축 및 실제 경로 얻기 === |
* SD Card에 저장된 그림 파일을 ImageView에 붙일 필요가 있을 때 사용. | |
<sxh java> | <sxh java> |
private String getRealImagePath (Uri uri) { | public class ImageUtil { |
Cursor cursor = getContentResolver().query(uri, null, null, null, null); | |
cursor.moveToFirst(); | private static final int MAX_IMAGE_SIZE = 1280; |
int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); | private static final int MAX_IMAGE_LENGTH = 720 * 1280; |
return cursor.getString(index); | |
| /** |
| * Image Uri → Compressed byte array |
| * (반복문으로 인하여 별도의 Thread 필요) |
| * @param context |
| * @param uri |
| * @return |
| * @throws Exception |
| */ |
| public static byte[] getCompressedByteArray(Context context, Uri uri) throws Exception { |
| BitmapFactory.Options options = new BitmapFactory.Options(); |
| |
| options.inSampleSize = calculateInSampleSize(options, 800, 800); |
| options.inJustDecodeBounds = false; |
| options.inPreferredConfig= Bitmap.Config.ARGB_8888; |
| |
| BufferedInputStream bin = new BufferedInputStream(context.getContentResolver().openInputStream(uri)); |
| Bitmap bitmap = BitmapFactory.decodeStream(bin, null, options); |
| |
| // resize (지정한 크기보다 작은 경우만) |
| if(bitmap.getWidth() * bitmap.getHeight() > MAX_IMAGE_SIZE * 2) |
| bitmap = resizeBitmap(bitmap, MAX_IMAGE_SIZE); |
| |
| int compressQuality = 100; |
| int streamLength; |
| |
| byte[] bitmapdata; |
| |
| String realPath = getRealImagePath(context, uri); |
| String extension = realPath.substring(realPath.lastIndexOf('.') + 1); |
| Bitmap.CompressFormat format; |
| switch (extension.toLowerCase()) { |
| case "jpg" : |
| case "jpeg" : |
| format = Bitmap.CompressFormat.JPEG; |
| break; |
| |
| case "png" : |
| case "gif" : |
| format = Bitmap.CompressFormat.PNG; |
| break; |
| |
| case "webp" : |
| format = Bitmap.CompressFormat.WEBP; |
| break; |
| |
| default: |
| throw new Exception("Unsupported format!"); |
| } |
| |
| do { |
| ByteArrayOutputStream baos = new ByteArrayOutputStream(); |
| bitmap.compress(format, compressQuality, baos); |
| bitmapdata = baos.toByteArray(); |
| streamLength = bitmapdata.length; |
| compressQuality -= 5; |
| } while (streamLength >= MAX_IMAGE_LENGTH); |
| |
| Log.d("compressBitmap", "Quality: " + compressQuality); |
| Log.d("compressBitmap", "Size: " + streamLength/1024+" kb"); |
| |
| return bitmapdata; |
| } |
| |
| private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { |
| final int height = options.outHeight; |
| final int width = options.outWidth; |
| int inSampleSize = 1; |
| |
| if (height > reqHeight || width > reqWidth) { |
| |
| final int halfHeight = height / 2; |
| final int halfWidth = width / 2; |
| |
| // Calculate the largest inSampleSize value that is a power of 2 and keeps both |
| // height and width larger than the requested height and width. |
| while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { |
| inSampleSize *= 2; |
| } |
| } |
| Log.d("inSampleSize", String.valueOf(inSampleSize)); |
| return inSampleSize; |
| } |
| |
| private static Bitmap resizeBitmap(Bitmap bitmap, int maxSize) { |
| float ratio = Math.min((float) maxSize / bitmap.getWidth(), (float) maxSize / bitmap.getHeight()); |
| int width = Math.round(ratio * bitmap.getWidth()); |
| int height = Math.round(ratio * bitmap.getHeight()); |
| return Bitmap.createScaledBitmap(bitmap, width, height, false); |
| } |
| |
| /** |
| * Uri를 이용해 실제 저장소 경로 얻기 |
| * @param context |
| * @param uri |
| * @return |
| */ |
| public static String getRealImagePath(Context context, Uri uri) { |
| Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); |
| cursor.moveToFirst(); |
| int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); |
| return cursor.getString(index); |
| } |
| |
| /** |
| * [0] : fileName |
| * [1] : extension |
| * @param filePath |
| * @return |
| */ |
| public static String[] getFileNameAndExtension(String filePath) { |
| return new String[] {filePath.substring(filePath.lastIndexOf(File.pathSeparator) + 1), filePath.substring(filePath.lastIndexOf('.') + 1)}; |
| } |
} | } |
| </sxh> |
| |
| |
| = Intellij - Git Bash 연동 = |
| |
| Tools -> Terminal |
| |
| <sxh bash> |
| "C:\Program Files\Git\bin\sh.exe" -login -i |
</sxh> | </sxh> |