scala-problem16-20

[TOC]

** 聲明**
該系列文章來自:http://aperiodic.net/phil/scala/s-99/
大部分內(nèi)容和原文相同,加入了部分自己的代碼配乱。
如有侵權(quán)泣侮,請及時聯(lián)系本人。本人將立即刪除相關(guān)內(nèi)容。

P16 (**) Drop every Nth element from a list.

要求

Example:

scala> drop(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))
res0: List[Symbol] = List('a, 'b, 'd, 'e, 'g, 'h, 'j, 'k)

方案

  • (1) 遞歸
def drop[T](n: Int, list: List[T]): List[T] = {
    def dropR(x: Int, ls: List[T]): List[T] = (x, ls) match {
        case (_, Nil)          => Nil
        case (1, head :: tail) => dropR(n, tail)
        case (_, head :: tail) => head :: dropR(x - 1, tail)
    }
    dropR(n, list)
}

P17 (*) Split a list into two parts.

要求

The length of the first part is given. Use a Tuple for your result.

Example:

scala> split(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))
res0: (List[Symbol], List[Symbol]) = (List('a, 'b, 'c),List('d, 'e, 'f, 'g, 'h, 'i, 'j, 'k))

方案

  • (1) take(n) + drop(n)
def split[T](x: Int, list: List[T]): (List[T], List[T]) = (list.take(x), list.drop(x))
  • (2) take(n) + drop(n) == splitAt(n)
def split2[T](x: Int, list: List[T]): (List[T], List[T]) = list.splitAt(x)
  • (3) 普通遞歸
def splitRecursive[T](x: Int, list: List[T]): (List[T], List[T]) =(x, list) match {
        case (_, Nil) => (Nil, Nil)
        case (0, ls)  => (Nil, ls)
        case (n, head :: tail) => {
            val (pre, post) = splitRecursive(n - 1, tail)
            return (head :: pre, post)
        }
    }

P18 (**) Extract a slice from a list.

要求

Given two indices, I and K, the slice is the list containing the elements from and including the Ith element up to but not including the Kth element of the original list. Start counting the elements with 0.

Example:

scala> slice(3, 7, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))
res0: List[Symbol] = List('d, 'e, 'f, 'g)

方案

  • (1) List內(nèi)置slice(廢話)
def slice[T](from: Int, to: Int, list: List[T]): List[T] = 
    list.slice(from, to)
  • (2) take + drop (實際上,內(nèi)置slice就是這么實現(xiàn)的)
def slice2[T](from: Int, to: Int, list: List[T]): List[T] = 
    list.drop(from).take(to - from)

P19 (**) Rotate a list N places to the left.

要求

Examples:

scala> rotate(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))
res0: List[Symbol] = List('d, 'e, 'f, 'g, 'h, 'i, 'j, 'k, 'a, 'b, 'c)

scala> rotate(-2, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))
res1: List[Symbol] = List('j, 'k, 'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i)

方案

  • (1) drop + take
def rotate[T](index: Int, list: List[T]): List[T] = {
    if (index < 0) {
        val i = list.length + index
        list.drop(i) ::: list.take(i)
    } else {
        list.drop(index) ::: list.take(index)
    }
}

def rotate2[T](index: Int, list: List[T]): List[T] = index match {
    case i if i < 0 => {
        val i = list.length + index
        list.drop(i) ::: list.take(i)
    }
    case _ => list.drop(index) ::: list.take(index)
}

P20 (*) Remove the Kth element from a list.

要求

Return the list and the removed element in a Tuple. Elements are numbered from 0.

Example:

scala> removeAt(1, List('a, 'b, 'c, 'd))
res0: (List[Symbol], Symbol) = (List('a, 'c, 'd),'b)

方案

  • (1) aplitAt
def removeAt[T](index: Int, list: List[T]): (List[T], T) = {
    if (index < 0) throw new NoSuchElementException
    val (prev, tail) = list.splitAt(index + 1)
    (prev.init ::: tail, prev.last)
}

另一寫法:

def removeAt2[T](n: Int, ls: List[T]): (List[T], T) = ls.splitAt(n) match {
    case (Nil, _) if n < 0 => throw new NoSuchElementException
    case (pre, e :: post)  => (pre ::: post, e)
    case (pre, Nil)        => throw new NoSuchElementException
}

  • (2) 遞歸(這個寫的很惡心)
def removeAt3[T](index: Int, list: List[T]): (List[T], T) = {
    if (index < 0) throw new NoSuchElementException

    (index, list) match {
        case (_, Nil)          => throw new NoSuchElementException
        case (0, head :: tail) => (tail, head)
        case (i, head :: tail) => (head :: removeAt3(i - 1, tail)._1, removeAt3(i - 1, tail)._2)
    }
}
  • (3) 遞歸
def removeAt4[T](index: Int, list: List[T]): (List[T], T) = {
    if (index < 0) throw new NoSuchElementException

    (index, list) match {
        case (_, Nil)          => throw new NoSuchElementException
        case (0, head :: tail) => (tail, head)
        case (_, head :: tail) => {
            val (prev, e) = removeAt4(index - 1, tail)
            (list.head :: prev, e)
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末扩淀,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子啤挎,更是在濱河造成了極大的恐慌驻谆,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,542評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件庆聘,死亡現(xiàn)場離奇詭異胜臊,居然都是意外死亡,警方通過查閱死者的電腦和手機伙判,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,596評論 3 385
  • 文/潘曉璐 我一進店門区端,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人澳腹,你說我怎么就攤上這事⊙詈危” “怎么了酱塔?”我有些...
    開封第一講書人閱讀 158,021評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長危虱。 經(jīng)常有香客問我羊娃,道長,這世上最難降的妖魔是什么埃跷? 我笑而不...
    開封第一講書人閱讀 56,682評論 1 284
  • 正文 為了忘掉前任蕊玷,我火速辦了婚禮邮利,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘垃帅。我一直安慰自己延届,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 65,792評論 6 386
  • 文/花漫 我一把揭開白布贸诚。 她就那樣靜靜地躺著方庭,像睡著了一般。 火紅的嫁衣襯著肌膚如雪酱固。 梳的紋絲不亂的頭發(fā)上械念,一...
    開封第一講書人閱讀 49,985評論 1 291
  • 那天,我揣著相機與錄音运悲,去河邊找鬼龄减。 笑死,一個胖子當(dāng)著我的面吹牛班眯,可吹牛的內(nèi)容都是我干的希停。 我是一名探鬼主播,決...
    沈念sama閱讀 39,107評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼鳖敷,長吁一口氣:“原來是場噩夢啊……” “哼脖苏!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起定踱,我...
    開封第一講書人閱讀 37,845評論 0 268
  • 序言:老撾萬榮一對情侶失蹤棍潘,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后崖媚,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體亦歉,經(jīng)...
    沈念sama閱讀 44,299評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,612評論 2 327
  • 正文 我和宋清朗相戀三年畅哑,在試婚紗的時候發(fā)現(xiàn)自己被綠了肴楷。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,747評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡荠呐,死狀恐怖赛蔫,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情泥张,我是刑警寧澤呵恢,帶...
    沈念sama閱讀 34,441評論 4 333
  • 正文 年R本政府宣布,位于F島的核電站媚创,受9級特大地震影響渗钉,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜钞钙,卻給世界環(huán)境...
    茶點故事閱讀 40,072評論 3 317
  • 文/蒙蒙 一鳄橘、第九天 我趴在偏房一處隱蔽的房頂上張望声离。 院中可真熱鬧,春花似錦瘫怜、人聲如沸术徊。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,828評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽弧关。三九已至,卻和暖如春唤锉,著一層夾襖步出監(jiān)牢的瞬間世囊,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,069評論 1 267
  • 我被黑心中介騙來泰國打工窿祥, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留株憾,地道東北人。 一個月前我還...
    沈念sama閱讀 46,545評論 2 362
  • 正文 我出身青樓晒衩,卻偏偏與公主長得像嗤瞎,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子听系,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,658評論 2 350

推薦閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,437評論 0 23
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗贝奇。 張土汪:刷leetcod...
    土汪閱讀 12,740評論 0 33
  • 1 大概是五年前的夏天,我回了趟家里靠胜,聽父親說是要跟祖輩和爺爺們告?zhèn)€別掉瞳。村里是這習(xí)俗,掙錢出門遠行浪漠,讀書漂泊異鄉(xiāng)陕习。...
    herensi閱讀 258評論 8 6
  • NSThread 這套方案是經(jīng)過蘋果封裝后的,并且完全面向?qū)ο蟮闹吩浮K阅憧梢灾苯硬倏鼐€程對象该镣,非常直觀和方便。但是...
    勇往直前888閱讀 333評論 0 0
  • 也許你不知道响谓, 每一次QQ上線的第一件事损合,就是看你在不在。 也許你不知道娘纷, 每一次我說“在干嘛?”塌忽,“在嗎?”,其...
    哈士奇2016閱讀 378評論 0 0