Welcome! 🙋‍♂️ View more

Engineering 💻/Algorithm

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

DeepFlame 2022. 8. 22. 21:24

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)))