Swift ^ Operation on Double - swift

I am trying to solve a challenge but the code keeps failing.
I need to perform a ^ operation on doubles. Challenge was if I call a function calculate(3,2,^) then I should get the result 9.
I tried the below code but failed with this error:
error: binary operator '^' cannot be applied to two 'Double' operands
Below is my Code:
func calc(a: Double, b: Double, op: Character) -> Double {
var c:Double
c = 0
if op == "+"
{
c = a + b
}
else if op == "-"
{
c = a - b
}
else if op == "*"
{
c = a * b
}
else if op == "/"
{
c = a / b
}
else if op == "%"
{
let rem = a.truncatingRemainder(dividingBy: b)
c = rem
}
else if op == "^"
{
let z = a ^ b
c = z
}
return c
}

^ is the bitwise XOR operator, not exponentiation.
Use the pow(_:_:) method instead:
else if op == "^"
{
c = pow(a, b)
}

try to use boucle For
for (let index = 0; index < b; index++) {
c= a*index;
}

Related

How to use string.split() without foreach()?

Write a program in Scala that reads an String from the keyboard and counts the number of characters, ignoring if its UpperCase or LowerCase
ex: Avocado
R: A = 2; v = 1; o = 2; c = 1; d = 2;
So, i tried to do it with two fors iterating over the string, and then a conditional to transform the character in the position (x) to Upper and compare with the character in the position (y) which is the same position... basically i'm transforming the same character so i can increment in the counter ex: Ava -> A = 2; v = 1;
But with this logic when i print the result it comes with:
ex: Avocado
R: A = 2; v = 1; o = 2; c = 1; a = 2; d = 1; o = 2;
its repeting the same character Upper or Lower in the result...
so my teacher asked us to resolve this using the split method and yield of Scala but i dunno how to use the split without forEach() that he doesnt allow us to use.
sorry for the bad english
object ex8 {
def main(args: Array[String]): Unit = {
println("Write a string")
var string = readLine()
var cont = 0
for (x <- 0 to string.length - 1) {
for (y <- 0 to string.length - 1) {
if (string.charAt(x).toUpper == string.charAt(y).toUpper)
cont += 1
}
print(string.charAt(x) + " = " + cont + "; ")
cont = 0
}
}
}
But with this logic when i print the result it comes with:
ex: Avocado
R: A = 2; V = 1; o = 2; c = 1; a = 2; d = 1; o = 2;
Scala 2.13 has added a very handy method to cover this sort of thing.
inputStr.groupMapReduce(_.toUpper)(_ => 1)(_+_)
.foreach{case (k,v) => println(s"$k = $v")}
//A = 2
//V = 1
//C = 1
//O = 2
//D = 1
It might be easier to group the individual elements of the String (i.e. a collection of Chars, made case-insensitive with toLower) to aggregate their corresponding size using groupBy/mapValues:
"Avocado".groupBy(_.toLower).mapValues(_.size)
// res1: scala.collection.immutable.Map[Char,Int] =
// Map(a -> 2, v -> 1, c -> 1, o -> 2, d -> 1)
Scala 2.11
Tried with classic word count approach of map => group => reduce
val exampleStr = "Avocado R"
exampleStr.
toLowerCase.
trim.
replaceAll(" +","").
toCharArray.map(x => (x,1)).groupBy(_._1).
map(x => (x._1,x._2.length))
Answer :
exampleStr: String = Avocado R
res3: scala.collection.immutable.Map[Char,Int] =
Map(a -> 2, v -> 1, c -> 1, r -> 1, o -> 2, d -> 1)

Extract coefficients from binomial expression entered as a string in Scala

I am trying to write a program that can find the roots of a quadratic equation using Scala. The input should be a quadratic equation in the form ax^2+bx+c (e.g: 5x^2+2x+3) as a string.
I managed to code the calculation of the roots but am having trouble extracting the coefficients from the input. Here's the code I wrote for extracting the coefficients so far:
def getCoef(poly: String) = {
var aT: String = ""
var bT: String = ""
var cT: String = ""
var x: Int = 2
for (i <- poly.length - 1 to 0) {
val t: String = poly(i).toString
if (x == 2) {
if (t forall Character.isDigit) aT = aT + t(i)
else if (t == "^") {i = i + 1; x = 1}
}
else if (x == 1) {
if (t forall Character.isDigit) bT = bT + t(i)
else if (t == "+" || t == "-") x = 0
}
else if (x == 0) {
if (t forall Character.isDigit) cT = cT + t(i)
}
val a: Int = aT.toInt
val b: Int = bT.toInt
val c: Int = cT.toInt
(a, b, c)
}
}
Simple solution with regex:
def getCoef(poly: String) = {
val polyPattern = """(\d+)x\^2\+(\d+)x\+(\d+)""".r
val matcher = polyPattern.findFirstMatchIn(poly).get
(matcher.group(1).toInt, matcher.group(2).toInt, matcher.group(3).toInt)
}
Does not handle all cases (e.g.: minus) and just throws an error if the input does not match the pattern, but it should get you going.

How does the while loop in this code work?

I am trying to complete a problem on LeetCode and I have found this solution in Swift but I am really not sure what happens in this while loop of the code :
func getSum(a: Int, _ b: Int) -> Int {
var a = a
var b = b
while b != 0 {
(a, b) = (a ^ b, (a & b) << 1)
}
return a
}
Thank you for any help.
(a, b) = (a ^ b, (a & b) << 1) is doing a tuple assignment. It can be broken down into:
let oldA = a
let oldB = b
a = oldA ^ oldB
b = (oldA & oldB) << 1
^ is the bit-wist exclusive-or (XOR) operator in Swift (and most C-like languages)
& is the bit-wise and (AND) operator in Swift (and most C-Like languages)
<< is the left bit shift operator. x << 1 means "bit-shift x to the left by 1"
As complement to #Alexander Momchliov's answer—which explains the bit-wise operators used—note also that you needn't use mutable local scope variables and a while loop in the getSum(...) function, but can use the same bit-operator calculations in recursive calls to the function itself, e.g.
func getSum(a: Int, _ b: Int) -> Int {
if b == 0 { return a }
return getSum(a ^ b, (a & b) << 1)
}

Simplifying nested ifs with multiple exit points in Scala?

There has to be a better way to do this.. I'm testing for a ray-triangle intersection and my code looks something like this
if(some condition) fail
else {
...
if(some other condition) fail
else {
...
intersection
}
}
with many nested ifs. It's disgusting. I'm doing this not to use any return statements. Is there an alternate control structure I could use here to manage the various method exit points?
You could use for comprehension:
val result: Option[BasicIntersection] = for {
edge1 <- Some(vertices(1) - vertices(0))
edge2 = vertices(2) - vertices(0)
P = ray.v cross edge2
determinant = edge1 dot P
if !(determinant > -Utils.EPSILON && determinant < Utils.EPSILON)
inv_determinant = 1.0/determinant
T = ray.p - vertices(0)
u = (T dot P) * inv_determinant
if !(u < 0 || u > 1)
Q = T cross edge1
v = (ray.v dot Q) * inv_determinant
if !(v < 0 || u + v > 1)
t = (edge2 dot Q) * inv_determinant
if !(t < Utils.EPSILON)
hit = ray.p + ray.v*t
} yield
if (hasUV) {
val d0 = Math.abs((hit - vertices(0)).length)
val d1 = Math.abs((hit - vertices(1)).length)
val d2 = Math.abs((hit - vertices(2)).length)
val uvAvg = (uv(0)*d0 + uv(1)*d1 + uv(2)*d2) / (d0 + d1 + d2)
new BasicIntersection(hit, edge1 cross edge2, t, uvAvg)
} else {
new BasicIntersection(hit, edge1 cross edge2, t)
}
result.getOrElse(new BasicIntersection()) // Your failure case

How to get unique elements from two lists of strings in scala?

I have two list to compare:
List one:
List("one","two","three","four")
List two:
List("one","two")
how can I get the unique values from these two lists?
If your two lists are r1 and r2, and assuming you want the values in each list that are not present in the other:
r1.filterNot(r2.contains) ::: r2.filterNot(r1.contains)
or
r1.diff(r2) ::: r2.diff(r1)
Turn them into sets, and get the intersection. You may then turn it back to Seq if you want, but first ask yourself if they had to be Seq in first place, instead of Set.
scala> List("one","two","three","four").toSet & List("one","two").toSet
res0: scala.collection.immutable.Set[String] = Set(one, two)
Use The difference operator for Set &~
http://www.scala-lang.org/api/current/scala/collection/immutable/Set.html
I use List(1, 2, 3, 4) ::: List(1, 2, 5) distinct for this issue. It returns List(1, 2, 3, 4, 5).
I would suggest using the following for O(m+n) running time (assumes input arrays are sorted).
def mergeUniqueSortedArrays( A: Array[String], B: Array[String] ): Array[String]= {
val n = A.length
val m = B.length
var C = Array[String]()
var i = 0
var j = 0
while (i < n && j < m) {
if (i == n) {
if ( B(j) != A(i-1) ) {
C :+= B(j)
}
j+=1
}
else if (j == m) {
if ( A(i) != B(j-1) ) {
C :+= A(j)
}
i+=1
}
else {
if ( A(i) < B(j) ) {
if (C.length == 0 || A(i) != C(C.length-1)) {
C :+= A(i)
}
i+=1
}
else if ( B(j) < A(i) ) {
if (C.length == 0 || B(j) != C(C.length-1)) {
C :+= B(j)
}
j+=1
}
else {
if (C.length == 0 || A(i) != C(C.length-1)) {
C :+= A(i)
}
i+=1
j+=1
}
}
}
return C
}
--
NOTE: If the input arrays are not sorted, then you can easily sort the input arrays and it will run in in O( max{(n + m), (n log n)}) time, assuming n>m.
NOTE: O(n + m) time technically assumes that string length is bounded by constant k, but you aren't going to get around that anyway.