[Algorithm] 알고리즘을 위한 Scala 기본 문법

2022. 8. 22. 21:24·Engineering/Algorithm

Scala란 함수형 객체지향 프로그래밍 언어로써 Spark를 사용할 때 빠른 성능을 이용할 수 있음으로 데이터 엔지니어링 역량에 필요한 언어입니다.

필자는 Scala언어와 친해지기 위해서 Scala 언어를 활용하여 많은 알고리즘 문제를 풀어보았습니다. 

https://github.com/DeepFlame-JR/Algorithm_Solving

 

GitHub - DeepFlame-JR/Algorithm_Solving: 알고리즘 문제 풀이

알고리즘 문제 풀이 . Contribute to DeepFlame-JR/Algorithm_Solving development by creating an account on GitHub.

github.com

 

아래에 알고리즘에 필요한 Scala 기본 문법에 대해서 정리해보겠습니다.

 

기본


var a = "Hello"// 일반 변수 (Readonly)
val b = 3 // 상수
var (a, b) = (1, "Hello") // 다중 할당

// 클래스 선언
class MyClass private(var name: String){
	def sayName(): Unit ={ // Unit = void
		println(name)
	}
}

 

 

배열


// 선언
var a = List(1,2,3) // 1,2,3
var a = List.fill(2){0} // 0,0
var a = List.empty[Type] // 빈 배열

// 편집
var a = List(1,2,3)
a :+= 5 // 1,2,3,5
a +:= 0 // 0,1,2,3,5
a = a ++ Array(10) // 0,1,2,3,5,10
a = a.updated(3, 9) // 0,1,2,9,5,10

a.take(2) // 0,1 (0~n-1)
a.drop(2) // 2,3,4,... (n~N-1)
a.slice(1,3) // 1,2 (start~end-1)

a = a.sortWith(_ < _) // 오름차순 정렬
println(a.mkString(",")) // print

// 2차원 배열
val matrix = Array.ofDim[Int](2,2)

 

 

조건문/반복문


// 반복문
for(x <- 1 until 3) 
    println("x 값:" + x)

for(item <- items)
	println(item)

// 2중 반복문
for(x <- 1 to 2; y <-1 to 9 ){
    print( x +"*" + y + "=" + x*y +", ")
}
// 1*1=1, 1*2=2, 1*3=3, 1*4=4, 1*5=5, 1*6=6, 1*7=7, 1*8=8, 1*9=9, 2*1=2, 2*2=4, 2*3=6, 2*4=8, 2*5=10, 2*6=12, 2*7=14, 2*8=16, 2*9=18,

// 조건문 1 line
x = if (a > b) a else b

 

 

기타 자료구조


import scala.collection.mutable._  // 기본값이 immutable이라 변수 내 값을 변경하려고 할 때 에러가 나타남

// HashMap
val map = Map[Char, Int]()
map += ("b" -> 2)
map -= "b"
map.toArray.sortBy(_._2)

// Queue
val queue = new Queue[Int]
queue.enqueue(1)
while(queue.nenEmpty)
	var cur = queue.dequeue()

// Stack
val stack = new Stack[Int]
stack.push(1)
var cur = stack.pop()

 

 

Map/Reduce


// map, flatMap (요소에 변화를 준다)
val fruits = Array("apple", "banana", "orange")
fruits.map(_.toUpperCase)  // APPLE, BANANA, ORANGE
fruits.flatMap(_.toUpperCase)  // A, P, P, L, E, B, A, N, A, N, A, O, R, A, N, G, E

val strings = List("1", "2", "foo", "3", "bar")
strings.map(toInt)  // Some(1), Some(2), None, Some(3), None
strings.flatMap(toInt)  // 1, 2, 3

// filter
val a = List(1,2,3,4)
a.filter(_%2==0) // 2,4
a.partition(_%2==0) // (List(2,4), List(1,2))

// reduce (단일 결과를 얻고싶다)
List(1,2,3).reduceLeft(_+_)  // 좌측_: 누적값, 우측_: 대상값
List(1,2,3).reduceRight(_+_)  // 좌측_: 대상값, 우측_: 누적값
List(1,2,3).foldLeft(4)(_+_)  // 4(시작값)+1+2+3

// Char Counter
val Counter = scala.collection.mutable.Map.empty[Char, Int]
str.distinct.toCharArray.map(x => Counter += (x -> str.count(_==x)))

 

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

[Leetcode/Python] 96. Unique Binary Search Trees  (0) 2022.05.24
[프로그래머스/Python] 경주로 건설  (0) 2022.03.25
[Algorithm] 정렬 알고리즘 간단 정리와 Python 구현 (버블정렬, 선택정렬, 퀵정렬, 병합정렬, 힙정렬)  (0) 2022.02.21
[알고리즘] 다이나믹 프로그래밍 (feat. Leetcode)  (0) 2022.02.06
[자료구조] 힙 (Heaps)  (0) 2022.02.05
'Engineering/Algorithm' 카테고리의 다른 글
  • [Leetcode/Python] 96. Unique Binary Search Trees
  • [프로그래머스/Python] 경주로 건설
  • [Algorithm] 정렬 알고리즘 간단 정리와 Python 구현 (버블정렬, 선택정렬, 퀵정렬, 병합정렬, 힙정렬)
  • [알고리즘] 다이나믹 프로그래밍 (feat. Leetcode)
AI건축가
AI건축가
LLMOps Engineer로 커리어를 쌓고 있습니다. 저만의 시점으로 AI를 해석하고자 노력합니다. 함께 배우고 성장하는 공간이 되었으면 좋겠습니다. 😊🚀
  • AI건축가
    DeepFlame AI
    AI건축가
  • 전체
    오늘
    어제
    • 분류 전체보기
      • AI
      • Ops
      • Engineering
        • Algorithm
        • CS
        • BigData
        • Tools
      • Personal
        • Toy Project
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    MSA
    Hive
    scala
    Cloud
    DP
    ec2
    AWS
    Python
    hadoop
    mongoDB
    mlops
    kubernetes
    Ai
    LeetCode
    db
    airflow
    Bio
    algorithm
    deepseek
    PostgreSQL
    세미나
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.6
AI건축가
[Algorithm] 알고리즘을 위한 Scala 기본 문법
상단으로

티스토리툴바