Easy wallpaper val numbers = List("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve","thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty") def wallPaper(l: Double, w: Double, h: Double): String = if(w*h*l==0) return "zero" else numbers(math.ceil((l*h*2+w*h*2)*1.15/(5.2)).toInt) Beginner Series #3 Sum of Numbers def getSum(a: Int, b: Int): Int = (List(a,b).min to List(a,b).max).sum Maximum Multiple def maxMultiple(d: Int, b: Int): Int = (d to b).filter(_%d==0).max //В лоб or def maxMultiple(d: Int, b: Int): Int = b - b % d or def maxMultiple(d: Int, b: Int): Int = (b / d) * d Printer Errors def printerError(s: String): String =s"${s.count(_ > 'm')}/${s.size}" or def printerError(s: String): String = s.count(_ > 'm').toString + "/" + s.length.toString Count the Digit def nbDig(n: Int, d: Int): Int = (0 to n).flatMap(i => (i*i).toString).count(j => j.asDigit==d) Over The Road def overTheRoad(address: Long, n: Long): Long = 2*n - address + 1 Simple Fun #8: Kill K-th Bit def killKthBit(n: Int, k: Int): Int = n & ~(1 << k - 1) // Очень изящное решение, но вы его не обоснуете скорее всего) or def killKthBit(n: Int, k: Int) :Int=if(n==0) 0 else Integer.parseInt(n.toBinaryString.substring(0, n.toBinaryString.length-k)+'0'+n.toBinaryString.substring(n.toBinaryString.length-k+1), 2) // Не такое красивое, зато понятнее Breaking chocolate problem def breakChocolate(n: Int, m: Int) = (n * m - 1).max(0) Count the divisors of a number def divisors(n: Int): Int = (1 to n).count(n % _ == 0) or def divisors(n: Int): Int = (1 to n).filter(n % _ == 0).length Sum of odd numbers def rowSumOddNumbers(n: Long): Long = n * n * n You're a square! import java.lang.Math.round import java.lang.Math.sqrt def isSquare(x: Int): Boolean = sqrt(x)==round(sqrt(x)) or def isSquare(x: Int): Boolean = math.sqrt(x).isWhole or def isSquare(x: Int): Boolean = math.sqrt(x).isValidInt Number of People in the Bus def number(busStops: List[(Int, Int)]): Int = busStops.map{case (on, off) => on - off}.sum Vowel Count def getCount(s: String): Int = s.count("aeiou".contains(_)) or def getCount(inputStr: String): Int = inputStr.count(Set('a', 'e', 'i', 'o', 'u')) Shortest Word def findShort(str: String): Int = str.split(' ').map(_.size).min or def findShort(str: String): Int = str.split(" ").map(_.length).min Two to One def longest(s1: String, s2: String): String = (s1 + s2).distinct.sorted Minimum Steps (Array Series #6) def minimumSteps(numbers: Array[Int], k: Int): Int = numbers.sorted.scanLeft(0)(_ + _).takeWhile(_ < k).size - 1 // Очень красивое решение, но нужно будет объяснить Alphabetical Addition // Решения лучше поменять, скорее алгоритм указан def addLetters(letters: List[Char]): Char = { val Ch = (letters.map(_.toInt).sum-letters.length*96)%26+96 if (Ch ==96) return 'z' Ch.toChar } or def addLetters(letters: List[Char]): Char = { val abc = 'z' +: ('a' to 'y') abc(letters.map(abc.indexOf).sum % 26) } Simple Fun #152: Invite More Women? def inviteMoreWomen(l: List[Int]): Boolean = l.sum > 0 V A P O R C O D E def encode(s: String): String = s.replace(" ", "").toUpperCase.mkString(" ") or def encode(s: String): String = s.filterNot(_.isWhitespace).toUpperCase.mkString(" ") Deodorant Evaporator // Решения очень индивидуальные def evaporator(content: Double, evapPerDay: Int, threshold: Int): Int = { (math.log(threshold / 100.0) / math.log(1 - evapPerDay / 100.0)).toInt + 1 } or def evaporator(content: Double, evapPerDay: Int, threshold: Int): Int = Iterator.iterate(100.0)(x => x * (1.0 - evapPerDay / 100.0)).takeWhile(_ >= threshold).length Coloured Triangles def triangle(row: String): String = if (row.length == 1) { row } else { val nextRow = row.substring(0, row.length - 1) .zip(row.substring(1, row.length)) .map { case (l, r) => Seq(l, r).distinct.sorted match { case Seq(x) => x case Seq('B', 'G') => 'R' case Seq('B', 'R') => 'G' case Seq('G', 'R') => 'B' } }.mkString("") triangle(nextRow) } и более изящное val colours = Set('R','G','B') def triangle(row: String): String = if(row.length == 1) row else triangle(row.zip(row.tail).map { case(c, d) if c == d => c case(c, d) => (colours - c - d).head }.mkString) Growth of a Population def nbYear(p0: Int, percent: Double, aug: Int, p: Int): Int = if (p0 >= p) 0 else 1 + nbYear((p0+p0*percent/100+aug).toInt,percent,aug,p) Speed Control def gps(interval: Int, distances: Array[Double]): Int = (distances.sliding(2).collect { case Array(a, b) => b - a }.maxOption.getOrElse(0d) * 3600 / interval).toInt Maximum Length Difference def mxdiflg(a1: List[String], a2: List[String]): Int = if (a1.size == 0 || a2.size == 0) -1 else a1.flatMap(x => a2.map(y => math.abs(x.size - y.size))).max Parts of a list def partList(xs: List[String]): List[(String, String)] = List.range(1, xs.size).map(i => (xs.take(i).mkString(" "), xs.drop(i).mkString(" "))) Mumbling // Решение лучше поменять индивидуальные def accum(s: String) = s.indices.map(i => s(i).toLower.toString * (i+1) capitalize).mkString("-") Complementary DNA def changer(s: Char) = s match { case 'A'=> 'T' case 'T'=>'A' case 'G'=>'C' case 'C'=>'G' } def makeComplement(dna: String): String = dna.map(changer) or def makeComplement(dna: String) = dna.map { case 'A' => 'T' case 'T' => 'A' case 'G' => 'C' case 'C' => 'G' } Fizz Buzz // Классическая задача, идея понятная, лучше переделать def fizzify(n: Int): List[String] = (1 to n) .map{x=>x match { case x if (x%5==0 && x%3==0) => "FizzBuzz" case x if (x%5==0 && x%3!=0) => "Buzz" case x if (x%5!=0 && x%3==0) => "Fizz" case x => x.toString } }.toList Easy Line def easyLine(n: Int): BigInt = { val prod: (Int, Int) => BigInt = (x, y) => (x to y).map(BigInt(_)).product prod(n + 1, 2 * n) / prod(1, n) } Small enough? - Beginner def smallEnough(n: Seq[Int], l: Int) = n.forall(_ <= l) Simple Fun #176: Reverse Letter def reverseLetter(str: String): String = str.filter(_.isLetter).reverse Sum of two lowest positive integers def sumTwoSmallest(numbers: List[Int]): Int = numbers.sorted.take(2).sum Sort array by string length def sortByLength(arr: Array[String]): Array[String] = arr.sortBy(_.length) Predict your age! //Очень красивое решение, но лучше изменить import scala.math.floor import scala.math.pow import scala.math.sqrt def predictAge(ages: Int*): Double = floor(sqrt(ages.map(pow(_, 2)).sum) / 2)