기본 콘텐츠로 건너뛰기

scala 3. 배열


scala에서 배열은 고정길이로 사용할건지, 가변으로 사용할건지로 구분을 둔다.

1. 고정길이 : Array
scala> val nums = new Array[Int](10)
nums: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
int형 10칸짜리 array 초기화했다.

값을 설정하고 싶을때는,
scala> val s = Array("hello","world");
s: Array[String] = Array(hello, world)

2. 가변길이 : ArrayBuffer
자바에서 ArrayList
C++에서는 vector
scala> val b = ArrayBuffer[Int]()
b: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

원소를 추가하거나 삭제할때는 대강 이렇다.
scala> b+=1
res3: b.type = ArrayBuffer(1)
scala> b+=(2,3,4,5)
res4: b.type = ArrayBuffer(1, 2, 3, 4, 5)
scala> b+=(1,2,3)
res5: b.type = ArrayBuffer(1, 2, 3, 4, 5, 1, 2, 3)
scala> b.trimEnd(3)
scala> b
res7: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4, 5)
scala> b.insert(2,99)
scala> b
res9: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 99, 3, 4, 5)
scala> b.remove(2)
res10: Int = 99
scala> b.remove(2,3)
scala> b
res12: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2)

3. array 탐색
보통 다른데서는 for문이나 while을 많이 쓴다.
scala> a
res28: Array[Int] = Array(2, 3, 5, 7, 11)
scala> for(elem <- a  if elem % 2 != 0) yield 2 * elem
res29: Array[Int] = Array(6, 10, 14, 22)

그런데 scala에서는 이렇게 할 수도 있다.
scala> a.filter(_ % 2 != 0).map(2 * _)
res30: Array[Int] = Array(6, 10, 14, 22)

fileter라는 함수가 내부적으로 for문과 동일하게 n번의 복잡도를 갖는지 확인을 해봐야겠지만, 뭔가 함수형 언어라는 느낌이 조금은 나는것 같다.

4. array 관련함수
scala> a
res31: Array[Int] = Array(2, 3, 5, 7, 11)

scala> a.sum
res32: Int = 28

scala> a.max
res33: Int = 11

scala> a.sorted
res34: Array[Int] = Array(2, 3, 5, 7, 11)

scala> a.mkString(" and ")
res35: String = 2 and 3 and 5 and 7 and 11

scala> a
res36: Array[Int] = Array(2, 3, 5, 7, 11)

sum, max, sorted 등등 쓸만한것 같다. mkstring같은것도 그렇고.

5. 다차원 배열
방법은 2가지다.
우선 ofDim이라는 메소드를 사용한다.
scala> val matrix = Array.ofDim[Array[Int]](2,3)
matrix: Array[Array[Array[Int]]] = Array(Array(null, null, null), Array(null, null, null))

두번째는 new를 사용하는법.
scala> val triangle = new Array[Array[Int]](3)
triangle: Array[Array[Int]] = Array(null, null, null)

scala> for(i <- 0 until triangle.length) triangle(i) = new Array[Int](i+1)
scala> triangle
res44: Array[Array[Int]] = Array(Array(0), Array(0, 0), Array(0, 0, 0))

댓글

이 블로그의 인기 게시물

메일서버가 스팸으로 취급받을때

설치한 메일서버를 통해 발송되는 메일이 스팸으로 들어가는 경우가 더러 있다. 이게 한번 들어가기는 쉬운데, 빠져나오기는 드럽게 힘든것 같다... 본인의 경우에는 우선 국내서비스에는 별 무리 없이 들어간다. (naver,daum 등) 그런데 해외메일 그중 Gmail, Hotmail 에는 에누리없이 스팸으로 간주되고 있었다. Gmail같은 경우에는 그래도 스팸함으로 발송은 제대로 되는반면에 Hotmail같은경우에는 아예 수신자체가 안되는 경우도 더러있다.. ㅡ,.ㅡ; 제일 좋은 방법은 Gmail,Hotmail에 전화걸어서 우리 메일서버 IP white Ip로 등록해달라!!! 하면 좋지만, 얘네들은 걸어봤자 자동응답기고, 문의채널은 구글 그룹스 게시판이 전부다.. 본론으로 들어가서. 해외 메일이 차단될 경우 내 매일서버ip가 스팸ip로 등록되 버린 경우일 수 있다. (본인처럼. ㅎ) 이것부터 조회 해보고 싶으면 RBL(real-time blocking List) 체크를 해야 하는데, RBL체크 해주는 사이트는 꽤 많이 있고, 그중 좀 깔끔해 보이는곳 하나 소개. http://www.anti-abuse.org/ 메일서버ip 입력하고 조회해보면 쭈루룩 리스트가 나온다. 그 중 빨간불이 들어온 부분이 메일 서버가 스팸서버가 된 각종 이유들이다.ㅋ 본인의 경우 CBL 때문에 걸렸는데, 내용은 아래와 같다. This IP address is HELO'ing as  "localhost.localdomain"  which violates the relevant standards (specifically: RFC5321). 메일서버 도메인에 별다른 작업을 안해놓아서 "localhost.localdomain" 으로 설정되어있었다. 만약 CBL만 바로 테스트 해보고 싶으면 http://cbl.abusea

[javascript] 특정시간에만 함수 실행

특정시간에만 팝업을 띄우려면?? 특정시간에만 로그인을 막으려면?? 특정시간에만 할일은 의외로 참 많다. 방법? 딱히 없다. 현재시간 구해서 시작시간, 종료시간 사이에 있을때 시작하는 수밖엔. if ((현재시간 > 시작시간) && (현재시간 < 종료시간)){ .. 팝업노출(); 공사페이지 리다이렉트(); 기타등등(); .. } 자바스크립트로 작성하면 다음과 같다. var startdate = "2014012008" ; var enddate = "2014012418" ; var now = new Date (); //현재시간 year = now. getFullYear (); //현재시간 중 4자리 연도 month = now. getMonth () + 1 ; //현재시간 중 달. 달은 0부터 시작하기 때문에 +1 if ((month + "" ). length < 2 ){ month = "0" + month; //달의 숫자가 1자리면 앞에 0을 붙임. } date = now. getDate (); //현재 시간 중 날짜. if ((date + "" ). length < 2 ){ date = "0" + date; } hour = now. getHours (); //현재 시간 중 시간. if ((hour + "" ). length < 2 ){ hour = "0" + hour; } today = year + "" + month + "" + date + "" + hour; //오늘 날짜 완성. / / 시간비교 i

스레드 동기화1 - syncronized

구현 스레드를 구현하는 방법은 2가지다. 1. Thread 클래스를 extends 한다. 2. Runnable 인터페이스를 implements 한다. 뭐 사실 Thread는 생성자의 변수로 Runnable을 취한다. public Thread (Runnable target) { init( null, target , "Thread-" + nextThreadNum () , 0 ) ; } 그리고 Runnable 인터페이스는 run() 이라는 단일함수를 갖는 인터페이스이다. @FunctionalInterface public interface Runnable { /** * When an object implementing interface <code> Runnable </code> is used * to create a thread, starting the thread causes the object's * <code> run </code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code> run </code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run () ; } 그렇기 때문에 람다식으로 표현이 가능한 것이다. 동기화 동기화는 동시에 같은자원의 접근을 제한하고자 할때 사용한다. 예를들어, 한 우물에서 물을 15번 길어야 하는 일을 해야할때 5명이서 3번만 하면 수고를 5배로 줄일수 있다. 그런데 우물은 하난데 동시에