Tuesday, October 16, 2018
greedy algorithm https://leetcode.com/problems/task-scheduler/description/
Sunday, October 7, 2018
typescript basic-types
Basic Types
link TypeScript-Handbook/Basic Types.md at master · Microsoft/TypeScript-Handbook · GitHub
Introduction
열거 형을 제공한다.
Boolean
1let isDone: boolean = false;
Number
- ECMAScript 2015에서 고새된 바이너리와 8진법도 가능하다
1234let decimal: number = 6
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0O744
String
- type스크립트에서도 싱글 qoute나 double qoute (쌍따옴표) 모두 사용 가능하다
- java에서는 상따옴표만 사용가능
12let color: string= "blue";
color = 'red';
- 템플릿도 사용 가능 하다 이때는 ` 기호를 사용해야한다. 템플릿자체가 멀티라인도 가능함
TypeScript example
12345let fullName: string = `Bob Bobbington`;
let age: number = 37;
let sentence: string = `Hello, my name is ${ fullName }.
I'll be ${ age + 1 } years old next month.`;
to Javascript
123var fullName = "Bob Bobbington";
var age = 37;
var sentence = "Hello, my name is " + fullName + ".\n\nI'll be " + (age + 1) + " years old next month.";
Array
- Typescript에서도 array를 사용할 수 있다.
- 선언하는 두가지 방법
123let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];
Tuple
- 튜플을 array의 형식처럼 지원한다. 튜플 안의 type은 동일할 필요가 없지만 사용 할때는 지정한 타입과 동일하게 사용해야함
123456// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error
Enum
- 도움이 되는 데이터타입이 enum 이다. c#처럼 numeric 값들을 조금더 친근하게 셋팅할 수 있다.
123enum Color {Red, Green, Blue}
let c: Color = Color.Green;
- javascript Converting
123456789var Color;
(function (Color) {
Color[Color["Red"] = 0] = "Red";
Color[Color["Green"] = 1] = "Green";
Color[Color["Blue"] = 2] = "Blue";
})(Color || (Color = {}));
var c = Color.Green;
{0: "Red", 1: "Green", 2: "Blue", Red: 0, Green: 1, Blue: 2}
Any
- Any 타입은 변수의 값이 숫자였다가 String값이 였다가 boolean 마음대로
1234567891011let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
// 오브젝트는 할당만 가능하고 임의의 메소드를 사용 못한다.
let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)
let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.
- 이것은 java에서는 상상도 못할 조금 신세계
123let list: any[] = [1, true, "free"];
list[1] = 100;
Void 타입??
- Void 는 리턴값이 없는 메소드에서 지정할 수 있고
- void 타입에 바인딩 할 수 있는 데이터는 오직 null 과 undefined만 적용 할 수 있다.
12345function warnUser(): void {
console.log("This is my warning message");
}
let unusable: void = undefined;
Null and Undefined
- null 과 undefined는 모든 타입의 서브 타입이다
- 즉 number에 null을 할당 할 수 있다.
- union type도 있긴 한데 나중에 확인 하겠다.
12345// Not much else we can assign to these variables!
let u: undefined = undefined;
let n: null = null;
// subtype 증명
Never
- 이해하기로는 반환값에 절대로 나타날수 없는 타입으로 사용할때 never를 사용한다.
123456789101112131415// Function returning never must have unreachable end point
function error(message: string): never {
throw new Error(message);
}
// Inferred return type is never
function fail() {
return error("Something failed");
}
// Function returning never must have unreachable end point
function infiniteLoop(): never {
while (true) {
}
}
Object
- 잘 이해가 안감 ㅎㅎㅎ
- object 는 number, string, boolean, symbol, null, undefined가 아닌 non-primitive type 이다
- Object.creat Api를 더 잘 표현할 수 있다.
123456789declare function create(o: object | null): void;
create({ prop: 0 }); // OK
create(null); // OK
create(42); // Error
create("string"); // Error
create(false); // Error
create(undefined); // Error
Type assertions
- 다른 언어의 형변환과 비슷하지만 특수 검사나 데이터 재구성을 하지 않으며 런타임시 영향을 미치지는 않는다 다만 컴파일러에서만 사용한다. 두가지 방법이 있는데 java처럼 angle-bracket syntax를 사용하는 방법이 있고 다른 하나는 as - syntax 를 사용하는 방법이 있다.
12345678// angle-bracket
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
// as syntax
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Saturday, October 6, 2018
오랫만에 풀어본 문제 serialized and desirialize
https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/
dfs 로 길을 갔었고 가는 곳 마다 흔적을 남겼고 다시 그 흔적을 따라 deserialized를 하면 풀리는 문제
Monday, September 17, 2018
async sync
sync와 async
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263// sync
@Test
public void zipTestSync(){
long start = System.currentTimeMillis();
// 비행편 가져오기
Flight flight = lookupFlight("a");
// 승객가져오기
Passenger passenger = findPassanger("person");
// 티켓 가져오기
Ticket ticket = getTicket(flight, passenger);
// 티켓 메일 보내기
sendEmail(ticket);
System.out.println(System.currentTimeMillis() - start);
}
// async
@Test
public void zipTestSingle(){
long start = System.currentTimeMillis();
// 비행기 lazyloading
Single<Flight> flight = Single.defer(() -> Single.just(lookupFlight("a")))
.subscribeOn(Schedulers.io());
// 승객 lazyloading
Single<Passenger> passenger = Single.defer(() ->Single.just(findPassanger("person")))
.subscribeOn(Schedulers.io());
// 비행기에서 승객을 zip으로 묶어서 다 로딩이된후 티켓을 가져오는데 .toBlocking으로 기다린다.
flight.zipWith(passenger, (f, p) -> getTicket(f, p))
.toBlocking()
.value().getFlightName();
System.out.println(System.currentTimeMillis()- start);
}
private Flight lookupFlight(String name) {
try {
Thread.currentThread().sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("lokkupFlight : " + name);
return Flight.builder().name(name).build();
}
private Passenger findPassanger(String name){
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("findPassanger");
return Passenger.builder().name(name).build();
}
private Ticket getTicket (Flight flight, Passenger passenger){
return Ticket.builder().flightName(flight.name).passengerName(passenger.getName()).build();
}
private void sendEmail(Ticket ticket){
System.out.println("sending ");
}
Friday, August 10, 2018
8개월간 클라이밍으로 인한 신체 변화
인증샷이다
지금부터 8개월전 클라이밍을 시작했고 지금 와서 인증샷을 찍었다
[변화]
몸무게 78kg -> 76kg -2kg
근육 30.1kg -> 31kg +1kg
체지방 24.7 -> 21.1 -3.3kg
체지방률 31.5% -> 27.7%
종합 점수 : 64점 -> 70점
엄청난 변화인것 같다.
클라이밍을 1년정도는 더 할 생각이 있는데
그때는 75점은 넘지 않을까 기대되네.
Thursday, July 5, 2018
regular expression 사용 예제
오랫만에 패턴 매칭해서 결과값 구하는것 찾음.
regular expression은 내가 짠거는 쉬운데 남이 짠거는 잘 안읽힘. ㅠ
T10 / name / AB12345
regular expression은 내가 짠거는 쉬운데 남이 짠거는 잘 안읽힘. ㅠ
Pattern p = Pattern.compile("(([a-zA-Z][0-9][0-9]?)\\s*[\\/]\\s*.{3}\\s*[\\/]\\s*)");Matcher m = p.matcher(line); while(m.find())
T10 / name / AB12345
Sunday, March 18, 2018
line encoding
I solved this problem with for
somebody solved this one with reguar expression
Given a string, return its encoding defined as follows:
somebody solved this one with reguar expression
Given a string, return its encoding defined as follows:
- First, the string is divided into the least possible number of disjoint substrings consisting of identical characters
- for example,
"aabbbc"is divided into["aa", "bbb", "c"]
- for example,
- Next, each substring with length greater than one is replaced with a concatenation of its length and the repeating character
- for example, substring
"bbb"is replaced by"3b"
- for example, substring
- Finally, all the new strings are concatenated together in the same order and a new string is returned.
Example
For
s = "aabbbc", the output should belineEncoding(s) = "2a3bc".
Input/Output
- [execution time limit] 3 seconds (java)
- [input] string sString consisting of lowercase English letters.Guaranteed constraints:
4 ≤ s.length ≤ 15. - [output] stringEncoded version of
s.
[Java] Syntax Tips
// Prints help message to the console
// Returns a string
//
// Globals declared here will cause a compilation error,
// declare variables inside the function instead!
String helloWorld(String name) {
System.out.println("This prints to the console when you Run Tests");
return "Hello, " + name;
}
Subscribe to:
Posts (Atom)
