서론

😊😊😊😊 화이팅!!

본론

이름을 포함한 문자열을 출력하래!!

결론

'Algorithm > CodeWars' 카테고리의 다른 글

Printer Errors by CodeWar  (0) 2021.05.06
Credit Card Mask By CodeWar  (0) 2021.05.02
Hello World By CodeWar  (0) 2021.05.02
Grasshopper - Terminal game move function By CodeWar  (0) 2021.05.02
Disemvowel Trolls By CodeWar  (0) 2021.05.02

서론

화이팅😊😊👍

본론

공장에서, 물건에  label 작업을 하고 있어.

a ~ m 값으로 !!

 

근데!!!!!!

error가 발생했데... 그래서, 나는 만약 error가 발생하면 이것을 수치화해서 String으로 변환해서 return해주는 것이 나의 역할이야.

 

아래와 같이, 출력하면 되는데,

분자에는 받아드린 문자열을 index 0부터 문자열의 길이(s.count) 만큼 한개 한개 n...z가 있는지 확인하고 만약 있다면 +1 !!!

한 값을 분자에다가 쏙!

 

분모는 받아드린 문자열의 길이를 넣어주자.

 

이렇게, 두개를 분수 모양으로 String  type으로 출력하면 됩니답!

 

1. 일단, 단위 테스트로 "x"가 있을때에, +1를 해보자!!

성공!!

 

결론

그럼, 이제 모든 케이스에 대해서 programming을 해보자!! 성공!!

'Algorithm > CodeWars' 카테고리의 다른 글

Returning Strings By CodeWar  (0) 2021.05.07
Credit Card Mask By CodeWar  (0) 2021.05.02
Hello World By CodeWar  (0) 2021.05.02
Grasshopper - Terminal game move function By CodeWar  (0) 2021.05.02
Disemvowel Trolls By CodeWar  (0) 2021.05.02

서론

credit card😊😊😊

재미겠다 이건 우리가 평소에 사용하는 algorithm이잔항

본론

okey, 요약하면 이거얌.

숫자를 string을 받아드린다음에, 마지막 4자리 숫자는 그래도 출력하고 나머지는 #으로 출력하는 거얌.

 

내 첫번째 생각은 5자리 이하 문자열 일때는 그대로 출력하자. 그리고 이러한 경우의 수가 아닐 경우에는,

 

받은 모든 문자열은 모두 #로 바꾸고 마지막 숫자 4자리 삭제하고 마지막 4번째 숫자는 그대로 출력할 문자열을 저장하고 

이둘을 합체!!!!!😊

그러면, 성공할듯

 

1. 시행착오

mask를 string를 집어 넣고, 각각의 index에 #을 넣을려고 했는데, 에러가 발생했다.

정확한 maching이 안됬다는 거....!! string.index를 예상했데. swift는 이렇게 접근하면 안될 것 같다.

2. 시행착오

apple 문서에서 본 append 함수를 사용하고자 했다. 그래서, 일단, 받아들인 string을 #으로 교체하는 것까지 성공!!

3. 시행 착오

그랬더니, #이 한개가 더 많아서 mask.count 범위 부분을 제외하고 조절했고, remove 함수를 이용하여, 문자열 일부분을 삭제하고자 했다. 이것 또한, string을 string.index로 바꿀 수 없데. 

 

4. 시행 착오

그래서, mask.count - 4 해버렸다.

5. 시행착오

append의 범위가 잘못 된것 같아.

6. 시행착오

일단, 문제 해결이 중요하니깐, index1를 정의해서 마지막 index값을 저장한다. 그것을 새로운 배열에 저장한다.

그리고 이것을 4번(처음을 포함한) 반복하자.

결론

'Algorithm > CodeWars' 카테고리의 다른 글

Returning Strings By CodeWar  (0) 2021.05.07
Printer Errors by CodeWar  (0) 2021.05.06
Hello World By CodeWar  (0) 2021.05.02
Grasshopper - Terminal game move function By CodeWar  (0) 2021.05.02
Disemvowel Trolls By CodeWar  (0) 2021.05.02

서론 

진로 고민으로 잠깐 멈추었지만, 다시 시작!!

본론

주어진 코드를 보고 잘못된 부분을 고치라는 문제임.

어디가 문제일까 봐보면, return이 misssing 되어야 한다고 해. 

그래서, return의 위치를 정확히 보면, 해결이 완료 될것같아.

switch 에서  case가 정해진 다음에, return을 해야하는데, default값에만 return에 있다는 것은, 해당된 case가 없을때에만 return을 한다는게 말이 안됨. ㅇㅋ??? 인정하시나요??

결론

서론 

오늘도 화이팅😊😊👍

 

본론

okey, 시계를 만들래. 어떤 시계냐면, 시, 분, 초를 입력 받아서 이것을 milli seocond로 바꾸어서 반환하는 거야.😊😊

일단, millisecond는 10^3이니깐,  초를 받았을때에는, 1000s가 되고, 분을 받았을 때에는 60*1000*m가 되고, 시를 받았을때에는 60 * 60 * 1000 * h 가 되니깐, 이것을 

다 더하면, 모가 된다>> 답이 된다.

그럼 이것도 if 문이 필요하네.

시행착오

나는 total을 바로 계산 한다음에, 반환을 했어. 그랬더니, 에러가 발생했어. Int로 반환하는 것을 못한데...

흠, 고민을 해봤는데, 과거에 강의에서 h,m,s와 같이 입력 받은 값은 let이라는 것이야. 그래서, 바로 반환을 안하고

한번 걸러서 반환을 했어.(결론 참고!!👍) 그랬더니, 성공!!

error
error

 

결론

solution

 

'Algorithm > CodeWars' 카테고리의 다른 글

Get Planet Name By ID By CodeWar  (0) 2021.05.02
Simple multiplication By CodeWars  (0) 2021.04.17
Transportation on vacation by CodeWar  (0) 2021.04.13
Is he gonna survive? by CodeWar  (0) 2021.04.11
Count the Monkey by CodeWar/ swift  (0) 2021.04.10

서론

오늘도 화이팅!!😊😊😊 이제, 10개 정도만 기본 문제 푼 다음에, 다음 단계로 넘어가자!!!

본론

가장 쉬운 문제입니다. 그래도 만만히 보면 큰코 다칠 수 도 있죠.

일단, 숫자를 배열로 받습니다. 이것을 합계를 더한 다음에, count를 활용하여 갯수로 나누어 줍니다.

그러면, 완료 입니다. 

필요한 건 if, sum, .count, for, += 정도가 되겠네여😊😊

결론

'Algorithm > CodeWars' 카테고리의 다른 글

Is he gonna survive? by CodeWar  (0) 2021.04.11
Count the Monkey by CodeWar/ swift  (0) 2021.04.10
Fake Binary by CodeWar  (0) 2021.04.08
Beginner - Lost Without a Map by CodeWar  (0) 2021.04.07
Century From Year by CodeWar  (0) 2021.04.07

서론 

쉬운 문제부터 차근차근 올라가자!!

 

본론

등차 수열이다, 😊😊 return ( sum +1)/2 해도 되는데, 근데.!!!!! 공식은 쓰고 싶지 않다 👍

programming적으로 생각해보자😊😊

그러면 for in 을 사용하자!!!

sum을 0으로 초기화하고 for 문을 활용해서 index를 1부터 n포함까지 범위를 결정하고 sum += index 하면 완성!!

구체적으로는, 

n에 1을 입력하면, index가 1이면 sum은 1이됨.

n에 2을 입력하면, index가 1이고 sum은 1이 되고, index가 2되면, sum은 기존의 sum과 더하여, 3이 된다.

...

결론

 

'Algorithm > CodeWars' 카테고리의 다른 글

Beginner - Lost Without a Map by CodeWar  (0) 2021.04.07
Century From Year by CodeWar  (0) 2021.04.07
Reversed Strings by CodeWar  (0) 2021.04.04
String repeat by CodeWar  (0) 2021.04.03
Calculate BMI  (0) 2021.04.02

Terminology

부호와 !와 같은 단항

+,*와 같은 이항 

(a ? b: c) 와 같은 삼항

 

Asssignment Operator

  1. let b = 10
  2. var a = 5
  3. a = b
  4. // a is now equal to 10

 

  1. let (x, y) = (1, 2)
  2. // x is equal to 1, and y is equal to 2,  it is tuple

 

  1. if x = y {
  2. // This isn't valid, because x = y doesn't return a value.
  3. }

Arithmetic Operators

스위프트는 c언어와 다르게 오버 플로우를 할 수 없다.

but, You can opt in to value overflow behavior by using Swift’s overflow operators (such as a &+ b). 

숫자는 물론, 물자열도 더할 수 있다.

like, "hello," + "Peter"

 

remainder operater

9 % 4 // equals 1

-9 % 4 // equals -1

Inserting -9 and 4 into the equation yields:

-9 = (4 x -2) + -1

 

unary minus operater

  1. let three = 3
  2. let minusThree = -three // minusThree equals -3
  3. let plusThree = -minusThree // plusThree equals 3, or "minus minus three"

compound operator

  1. var a = 1
  2. a += 2
  3. // a is now equal to 3

하지만, 이렇게는 작성할 수 없다.( 연산자를 두개 동시에)

 let b = a += 2.

 

 comparison operators

  1. (1, "zebra") < (2, "apple") // true because 1 is less than 2; "zebra" and "apple" aren't compared
  2. (3, "apple") < (3, "bird") // true because 3 is equal to 3, and "apple" is less than "bird"
  3. (4, "dog") == (4, "dog") // true because 4 is equal to 4, and "dog" is equal to "dog"
  1. ("blue", -1) < ("purple", 1) // OK, evaluates to true
  2. ("blue", false) < ("purple", true) // Error because < can't compare Boolean values

ternary conditional operator

하지만, 복잡해 질 수 있으니 너무 많이 사용하지는 말자.

  1. let contentHeight = 40
  2. let hasHeader = true
  3. let rowHeight = contentHeight + (hasHeader ? 50 : 20)
  4. // rowHeight is equal to 90

The example above is shorthand for the code below:

  1. let contentHeight = 40
  2. let hasHeader = true
  3. let rowHeight: Int
  4. if hasHeader {
  5. rowHeight = contentHeight + 50
  6. } else {
  7. rowHeight = contentHeight + 20
  8. }
  9. // rowHeight is equal to 90

Nil-coalescing operator

 

(a ?? b) 에서  a의 값의 따라서, 결과가 달라짐.

만약, a가 value를 가지면 a를 return하고 a가 nil이면, b를 return 한다.

  1. let defaultColorName = "red"
  2. var userDefinedColorName: String? // defaults to nil
  3.  
  4. var colorNameToUse = userDefinedColorName ?? defaultColorName
  5. // userDefinedColorName is nil, so colorNameToUse is set to the default of "red"

 

  1. userDefinedColorName = "green"
  2. colorNameToUse = userDefinedColorName ?? defaultColorName
  3. // userDefinedColorName isn't nil, so colorNameToUse is set to "green"

 

 

range operator

 

< 이거를 가지는 것은 포함하지 않음.

시작과 끝을 명확히 할 것.

for index 1...5 in {

print(index)

}

// 1 2 3 4 5 

 

  1. for index in 1...5 {
  2. print("\(index) times 5 is \(index * 5)")
  3. }
  4. // 1 times 5 is 5
  5. // 2 times 5 is 10
  6. // 3 times 5 is 15
  7. // 4 times 5 is 20
  8. // 5 times 5 is 25
  1. let names = ["Anna", "Alex", "Brian", "Jack"]
  2. let count = names.count
  3. for i in 0..<count {
  4. print("Person \(i + 1) is called \(names[i])")
  5. }
  6. // Person 1 is called Anna
  7. // Person 2 is called Alex
  8. // Person 3 is called Brian
  9. // Person 4 is called Jack

 

  1. for name in names[2...] {
  2. print(name)
  3. }
  4. // Brian
  5. // Jack
  6.  
  7. for name in names[...2] {
  8. print(name)
  9. }
  10. // Anna
  11. // Alex
  12. // Brian
  1. for name in names[..<2] {
  2. print(name)
  3. }
  4. // Anna
  5. // Alex
  1. let range = ...5
  2. range.contains(7) // false
  3. range.contains(4) // true
  4. range.contains(-1) // true

logical operator

  1. if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {
  2. print("Welcome!")
  3. } else {
  4. print("ACCESS DENIED")
  5. }
  6. // Prints "Welcome!"

explicit parentheses

 

( )를 삽입 함으로써, 가독성을 높였다. 프로그래머의 의도를 명확히 알 수 있다.

  1. if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {
  2. print("Welcome!")
  3. } else {
  4. print("ACCESS DENIED")
  5. }
  6. // Prints "Welcome!"

 

 

'IOS > IOS Documentation' 카테고리의 다른 글

Collection types  (0) 2021.03.08
Strings and Characters  (0) 2021.03.06
The BASIC  (0) 2021.03.03
단순한 가치  (0) 2020.08.30
스위프트 여행  (0) 2020.08.30

Intro

스위프트는  ios 환경을 위한 새로운 언어이다. 이것은 c,c++와 비슷하기 때문에 배우는데 큰 어려움은 없을 것이다.

 

swift는 세개의 데이터 타입을 제공한다. 

 

array, tuple, and dictionary이다.

 

s는 원하는 타입을 전달하는데에 type safty를 하면 실수로 다른 타입을 전달하는 일이 없을 것입니다.

 

constants and variable 

let 은 변하지 않는 것 var 은 변하는 것 , 둘다 초기화 해야됨. 

아 글구 콤마를 사용해서 한줄에 정의 가능함. like var x = 0.0, y=0.0, z=0.0

 

type annotations

 var welcomemessage : String

“Declare a variable called welcomeMessage that’s of type String.” 

 

comments

// or /*comments*/

 

semicolon 

let rat ="🐹" ;print(rat) 

 

integer 

integer bounds 

let maxvalue = UInt.max

//256

let minvalue = UInt.min

//0

 

floating number

 

float      32bit

double.  64bit

 

type safety and type inference

 

int나 double같은 디테일한 사항은 컴파일하면서 알아서 지정해준다. 사용자는 오직 let과 var만 신경쓰면 된다.

 

  • 1.25e2 means 1.25 x 102, or 125.0.
  • 1.25e-2 means 1.25 x 10-2, or 0.0125.
  • 0xFp2 means 15 x 22, or 60.0.
  • 0xFp-2 means 15 x 2-2, or 3.75.
  1. let decimalDouble = 12.1875
  2. let exponentDouble = 1.21875e1
  3. let hexadecimalDouble = 0xC.3p0
  1. let paddedDouble = 000123.456
  2. let oneMillion = 1_000_000
  3. let justOverOneMillion = 1_000_000.000_000_1

numeric type conversion

최적화나 용량이 아주 큰 상황이 아니라면, 대부분을 int를 사용해라. 

 

 

type alises

타입을 스스로 지정할 수 있다.

  1. typealias AudioSample = UInt16
  1. var minAmplitudeFound = AudioSample.min
  2. // minAmplitudeFound is now 0

booleans

true 혹은 false이고 데이터 타입을 지정하지 않아도 된다.

let i 

if i {

 it will not be working successfully 

}

 

let i

if i==1{

 it will be working successfully 

}

 

tuples

다른 종류의 데이터를 한 변수에 저장할 수 있다. 주로 웹페이지에서 검색의 성공 혹은 실패를 사용자가 확인 하는데에 사용된다.

더 복잡한 것은 struct와 class을 사용하자.

  1. let http404Error = (404, "Not Found")
  2. // http404Error is of type (Int, String), and equals (404, "Not Found")
  1. let (statusCode, statusMessage) = http404Error
  2. print("The status code is \(statusCode)")
  3. // Prints "The status code is 404"
  4. print("The status message is \(statusMessage)")

 

  1. // Prints "The status message is Not Found"
  1. let (justTheStatusCode, _) = http404Error
  2. print("The status code is \(justTheStatusCode)")
  3. // Prints "The status code is 404"
  1. print("The status code is \(http404Error.0)")
  2. // Prints "The status code is 404"
  3. print("The status message is \(http404Error.1)")
  4. // Prints "The status message is Not Found"

 

  1. let http200Status = (statusCode: 200, description: "OK")
  1. print("The status code is \(http200Status.statusCode)")
  2. // Prints "The status code is 200"
  3. print("The status message is \(http200Status.description)")
  4. // Prints "The status message is OK"

 

optional 

값이 없을 수 있는 경우에 사용.

  1. let possibleNumber = "123"
  2. let convertedNumber = Int(possibleNumber)
  3. // convertedNumber is inferred to be of type "Int?", or "optional Int"

int이거나 아니거나 

 

error handling 

실행중에 에러를 맞이했을 때, 어떻게 대처 할 것인가?에 대한 답

  1. func makeASandwich() throws {
  2. // ...
  3. }
  4.  
  5. do { 
  6. //no error was thrown
  7. try makeASandwich()
  8. eatASandwich()
  9. } catch SandwichError.outOfCleanDishes {
  10. // error was thrown
  11. washDishes()
  12. } catch SandwichError.missingIngredients(let ingredients) {
  13. buyGroceries(ingredients)
  14. }

 

assertions and preconditions

 

이것은 error handling와 같이 잘못된 가정이라던가 잘못된 것을 올바르게 고치지는 못한다. 다만, 확일할 뿐이다.

 

주장은 개발 중에 실수나 잘못된 가정을 찾는 데 도움이 되고 전제 조건은 생산의 문제를 탐지하는 데 도움이 됩니다.

 

주장과 전제조건의 차이는 검사할 때 나타난다. 

 

주장은 디버그 빌드에서만 확인되지만 전제 조건은 디버그 및 프로덕션 빌드에서 모두 확인됩니다. 

 

생산 빌드에서는 주장 내부의 상태를 평가하지 않습니다. 즉, 프로덕션 성능에 영향을 주지 않으면서 개발 프로세스 중에 원하는 만큼 주장을 사용할 수 있습니다

 

assertions

false일 경우, 메세지를 전달함.

  1. let age = -3
  2. assert(age >= 0, "A person's age can't be less than zero.")
  3. // This assertion fails because -3 isn't >= 0.

 

  1. if age > 10 {
  2. print("You can ride the roller-coaster or the ferris wheel.")
  3. } else if age >= 0 {
  4. print("You can ride the ferris wheel.")
  5. } else {
  6. assertionFailure("A person's age can't be less than zero.")
  7. }

preconditions

조건이 거짓일 수도 있지만, 반드시 참이어야 할때, 올바른 함수 값을 주었는가??

  1. // In the implementation of a subscript...
  2. precondition(index > 0, "Index must be greater than zero.")

'IOS > IOS Documentation' 카테고리의 다른 글

Strings and Characters  (0) 2021.03.06
Basic Operators  (0) 2021.03.04
단순한 가치  (0) 2020.08.30
스위프트 여행  (0) 2020.08.30
Let's start  (0) 2020.08.30

+ Recent posts