scala programming question for importing other objects

I am working on the examples of 99 Scala problems. The question p11, d. H. The modified run length coding. In the second line, the object is imported from p10 code "import P10.encode". My question here is when it comes in the line of code below

encode (ls) map {t => if (t._1 == 1) t._2 otherwise t}

I know that he maps the P10 code definition, but how does he know where to get the t-value? Does it work on the output when z. For example, the output of p10 is List ((1,1), (2,4), (1,3)) for input encoding (List (1,4,4,3)). or something else? Please enlighten me

scala – Elegant way to express nested cats. Either T / OptionT code

We have a pretty unattractive code here that looks asynchronously at whether a value already exists, and if it does not, it has a side effect. This ultimately leads to a possible error.

It seems to me that there has to be a better way than packing and unpacking OptionTs. Any suggestions?

def persistValue (value: DtoA): either T[Future, Error, Unit] = ???
val maybeCachedValue: OptionT[Future, DataTypeA] = ???
val Result: OptionT[Future, Error] = OptionT (
maybeCachedValue.value
.flatMap {
case Some (_) => Future.successful (None)
case None => persistValue (someDto) .swap.toOption.value
}
)

scala – How do I rename the file saved in a Datalake in Azure?

I tried to merge two files in a datalake using scala into data blocks and saved them in datalake with the following code:

val df = sqlContext.read.format ("com.databricks.spark.csv"). Option ("Header", "true"). Option ("inferSchema", "true") .load ("adl: // xxxxxxxx) / Test / CSV")
df.coalesce (1) .write.
Format ("com.databricks.spark.csv").
Mode ("Overwrite").
Option ("Header", "True").
save ("adl: //xxxxxxxx/Test/CSV/final_data.csv")

However, the file final_data.csv will be saved as a directory instead of a file with multiple files, and the actual CSV file will appear as & # 39; part-00000-tid-dddddddddd-xxxxxxxxxx.csv & # 39; saved.

How do I rename this file so I can move it to another directory?

Interview Questions – Extend spreadsheets to cell lists in Scala

problem

Spreadsheet cells are referenced by column and row identifiers. Columns are labeled with letters beginning with "A", "B", "C", …; The lines are numbered from 1 in ascending order. Write a function that contains a string that identifies a range of cells in a spreadsheet and returns an ordered list of cells that make up that range.

Example:

"A3: D5" -> ["A3", "A4", "A5", "B3", "B4", "B5", "C3", "C4", "C5", "D3", "D4", "D5"]
"A3: D4" -> ["A3", "A4", "B3", "B4", "B5", "C3", "C4", "C5", "D3", "D4"]

Here's the Scala implementation of the same,

Import scala.language.postfixOps

object PrintSpreadSheet extends App {

val validAlphabets = (& # 39; A & # 39; to & # 39; Z & # 39;). toSeq

def cells (range: string): Seq[String] = {
val corners = (area distribution ":") flatMap {corner =>
Seq (corner, head, corner)
}
val row = (Corner filter (r => validAlphabets.contains (r))) sorted
val cols = (Corner filter (c =>! validAlphabets.contains (c))) sorted

(Lines, head to lines, last) flatMap {r =>
(cols.head to cols.last) map {c =>
r.toString + ":" + c.toString
}
}
}
Cells ("A1: D5") for each print
}

Interview questions – Print the spreadsheet cell in Scala

problem

Spreadsheet cells are referenced by column and row identifiers. Columns are labeled with letters beginning with "A", "B", "C", …; The lines are numbered from 1 in ascending order. Write a function that contains a string that identifies a range of cells in a spreadsheet and returns an ordered list of cells that make up that range.

Example:

"A3: D5" -> ["A3", "A4", "A5", "B3", "B4", "B5", "C3", "C4", "C5", "D3", "D4", "D5"]
"A3: D4" -> ["A3", "A4", "B3", "B4", "B5", "C3", "C4", "C5", "D3", "D4"]

Here's the Scala implementation of the same,

Import scala.language.postfixOps

object PrintSpreadSheet extends App {

val validAlphabets = (& # 39; A & # 39; to & # 39; Z & # 39;). toSeq

def cells (range: string): Seq[String] = {
val corners = (area distribution ":") flatMap {corner =>
Seq (corner, head, corner)
}
val row = (Corner filter (r => validAlphabets.contains (r))) sorted
val cols = (Corner filter (c =>! validAlphabets.contains (c))) sorted

(Lines, head to lines, last) flatMap {r =>
(cols.head to cols.last) map {c =>
r.toString + ":" + c.toString
}
}
}
Cells ("A1: D5") for each print
}

Strings – Scala Word Ladder

The problem is inherited from the leet code (and changed slightly).

Two words (beginWord and endWord) and a word list of a dictionary
Prints the shortest transformation and counts from beginWord to
endword, so that:

Only one letter can be changed at a time. Every word has to be changed
exist in the word list. Note that beginWord is not a transformed word.
Note:

Returns an empty list if no such transformation sequence exists.
All words have the same length.
All words contain only lowercase letters.
You may not accept duplicates in the word list.
You can assume that beginWord and endWord are not empty and are not identical.

Example –

Entrance:
beginWord = "hits",
endword = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output:
hit -> hot -> dot -> dog -> cog
4

Scala code

import scala.collection.mutable

object WordLadder extends App {
val dictionary = set (hot, dot, dog, lot, log, cog)
def oneStepAway (w1: String, w2: String): Boolean = (w1 diff w2) .length == 1
def calculateStep (Start: String, End: String): Int = {
val lookupTable = mutable.Queue[(String, Int, Array[String])]((Start, 0, array)[String]()))
var matchNotFound = true
var stepsTaken = 0
while (matchNotFound && lookupTable.nonEmpty) {
val (word, distance, path) = lookupTable.dequeue ()
if (word == end) {
matchNotFound = false
stepsTaken = distance
println (path ++ array (end) mkString ("->"))
} else {
Dictionary foreach {entry =>
if (oneStepAway (word, entry) &&! lookupTable.find (_._ 1 == entry) .isDefined) {
lookupTable.enqueue ((entry, distance + 1, path ++ array (word)))
}
}
}
}
if (! matchNotFound) stepsTaken else -1
}
println (calculateSteps ("hit", "cog"))
}

Interview questions – Number of possible BST with given key number n in Scala

Problem –
Total number of possible binary search trees with n keys.

for n = 0, only one BST is possible (that is, zero or empty tree)

for n = 1, only one BST is possible
for n = 2, two BSTs are possible

for n = 3, five different BSTs are possible.

And so on.

Solution in Scala –

import scala.collection.mutable


object BSTCount extends App {
// count (6) = count (5) * count (0) + count (4) * count (1) + count (3) * count (2)
// count (2) .count (3) + count (1) * count (4) + count (0) * count (5)
val lookup = mutable.HashMap[Int,Int]((0,1), (1,1), (2,2))
def BSTCount (n: Int): Int = {
n match {
Case 0 => 1
Case 1 => 1
Case 2 => 2
case _ =>
if (! (lookup contains n)) {
val r = ((0 to n) map {i =>
Look up + = i -> BSTCount (i)
Lookup + = (n-i-1) -> BSTCount (n-i-1)
Lookup (i) * Lookup (n-i-1)
}).Total
Look up + = (n -> r)
}
Lookup (s)
}
}

(1 to 10) foreach (num => println (num + "->" + BSTCount (num)))

}

It produces the following output –

1 -> 1
2 -> 2
3 -> 5
4 -> 14
5 -> 42
6 -> 132
7 -> 429
8 -> 1430
9 -> 4862
10 -> 16796

Interview Questions – Minimal Steps to Achieve a Goal by a Knight In Scala

In a size N (square matrix) chessboard, the position of the knight and the position of a target determine minimal steps (both number and exact steps) from the start to the finish of a knight.

If it is not possible to reach the specified position, return -1 as a step number.

Here's the implementation in Scala (assuming N = 4 or 4X4 chessboard).

import scala.collection.mutable._

object KnightMoves extends App {
Case class Pos (line: Int, Col: Int)
val size = 4

def calculateMoves (from: Pos, Target: Pos): (Int, Seq[Pos]) = {
val pendingPos = collection.mutable.Queue[Pos](from)
val positionVisited = collection.mutable.HashMap[Pos(IntSeq[Pos(IntSeq[Pos(IntSeq[Pos(IntSeq[Pos])](from -> (0, Seq ()))
var targetReached = false

while (pendingPos.nonEmpty &&! targetReached) {
val p = pendingPos.dequeue ()
possibleMoves (p) for all {position =>
if (position == target) {
targetReached = true
} else if (! (positionVisited contains position)) {
pendingPos Enqueue position
}
positionVisited + = position -> ((positionVisited (p) ._ 1 + 1, (positionVisited (p) ._ 2 ++ Seq (p))))
}
}
if (targetReached) positionVisited (target) else (-1, Seq ())
}

def isValidPos (position: Pos): Boolean =
((0 to size) contains position.row) && ((0 to size) contains position.col)

def possibleMoves (Position: Pos): List[Pos] =
List (Pos (position lines - 2, position scale + 1),
Pos (position line - 2, position column - 1),
Pos (position line + 2, position column + 1),
Pos (position line + 2, position.col - 1),
Pos (position.row - 1, position.col + 2),
Pos (Position line - 1, Position.col - 2),
Pos (position line + 1, position column + 2),
Pos (position line + 1, position column - 2)
) filter (pos => isValidPos (pos))

println (calculateMoves (Pos (0,1), Pos (0,0)))
println (calculateMoves (Pos (0,1), Pos (0,2)))
}

Program generate the following output for two test instructions below.

(3, ArrayBuffer (Pos (0,1), Pos (2,0), Pos (1,2)))
(3, ArrayBuffer (Pos (0,1), Pos (2,2), Pos (1,0)))

Interview questions – Next 3Sum in Scala

This question comes from the leet code.

Find three if you have an array number of n integers and an integer destination
integers in numbers so that the sum is closest to the goal. Give that … again
Sum of the three integers. You can assume that every input would have
exactly one solution.

Given array numbers = [-1, 2, 1, -4]and destination = 1.

The closest sum to the goal is 2. (-1 + 2 + 1 = 2).

I need feedback on my solution from the perspective of the programming interview (where they rate you for solution quality).

My first solution is this (and preferred)

scala> ((List (-1,2,1, -4) .combinations (3) .map (_. sum) map (sum => (sum, Math.abs (1-sum))) toList) sortWith ( _._ 2 <_._ 2)). Head._1
Res166: Int = 2

However, I assume the interviewer might ask me to implement combinations (and one provided by the library). So I implemented it that way

def combinations (l: list[Int], c: Int): list[List[list[Liste[List[Int]]= {
if (c == 1) {l map {r => list (r)}} else {
I think
Case zero => List.empt
Fall head :: tail =>
(Combinations (tail, c-1) map {r => head :: r}) ++ combinations (tail, c)
}
}
}

I think that's good enough to solve this problem (from the point of view of the interview).

But after I solved that, I came across a question to SO, where people are trying to solve the problem without going into O (n3) Complexity.
Please suggest how you would solve it.

Please also suggest to me how I should deal with this scenario in which I think the solution I have given is best for the problem.

Recursion – Replace the array element by multiplying the neighbors in Scala

Update the index with a multiplier of the previous and next integers.

    Input: 2, 3, 4, 5, 6
Output: 2 * 3, 2 * 4, 3 * 5, 4 * 6, 5 * 6

This is followed by a Scala implementation for the same. Please check.

import scala.util.Random

object NeighborMultiplication extends App {
Val Numbers = List.Fill (10) (Random.nextInt (10))

println (numbers mkString ",")

def multiplication (l: list[Int], carryOver: int = 1, useCarryOver: boolean = false): list[Int] = l match
Case zero => list ()
case x :: Nil => list (carryover * x)
case x :: y :: Nil => list (carryOver * x * y, y * x)
case x :: y :: z :: Nil => list (carryOver * x * y, x * z, y * z)
Case x :: y :: z :: tail =>
if (useCarryOver) list (carryOver * y, x * z, y * tail.head) ++ multiplication (tail, z, true)
else List (x * y, x * z, y * tail.head) ++ Multiplication (tail, z, true)
}


println (multiplication (numbers) .mkString (","))


}