scala for loop issue with assignment - scala

val u = Array(1,2,3,4,5)
var outsideValue = 7
for{
i <- 0 until u.size
_= outsideValue = u(i)
if(outsideValue == 2)
j <- u
}
{
println(s"$outsideValue $j")
`Expected output is it should print all combination of Array with value 2, but it is not printing !!!`
NOTE: I know we can do it in simpleway
But i want to know why above code is not working

Let us first start with how will you do this in any other language,
Java
String[] u = {1, 2, 3, 4, 5};
for (int i = 0; i < u.length(); i++) {
if (u[i] == 2) {
for (int j = 0; j < u.length(); j++) {
System.out.println("" + u[i] + ", " + u[j]);
}
}
}
JavaScript,
var u = [1, 2, 3, 4, 5];
for (var i = 0; i < u.length(); i++) {
if (u[i] == 2) {
for (var j = 0; j < u.length(); j++) {
console.log("" + u[i] + ", " + u[j]);
}
}
}
And you can do it the more or less same way in Scala with for-loop. (Not to be confused with the concept of for-comprehension)
val u = new Array(1, 2, 3, 4, 5)
for (i <- 0 until u.length()) {
if (u(i) == 2) {
for (j <- 0 until u.length()) {
println(s"${u(i)}, ${u(j)})
}
}
}
If you want to use for-comprehension then,
val u = Array(1, 2, 3, 4, 5)
for {
i <- u.filter(_ == 2)
j <- u
} println(s"$i, $j")
As for "why your code does not work ?". The reason is that you are trying to use for-comprehension without really understanding these, which lead to a very strange looking and incorrect code.
for-comprehension in Scala works by using combinations of map / flatMap / foreach / flatten in various ways depending on the usage.
In this case, the above for-comprehension version is equivalent to the following foreach based version,
val array = Array(1, 2, 3, 4, 5)
array.filter(_ == 2).foreach(i => {
array.foreach(j => println(s"$i, $j")
})

Related

how to calculate sum of every n values in a list?

I have a list that contains some values I want to calculate the sum of every 4 items in this list and then I have to put it in a list.
for example:
list 1=[1,2,3,4,5,6,7,8]
output= [10,26]
You can play with snippet.
final List<int> list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
final List<List<int>> subLists = [];
for (int i = 0; i < list.length / 4; i++) {
final start = i * 4;
final end = i * 4 + 4;
subLists
.add(list.sublist(start, end > list.length ? list.length : end));
}
print(subLists); //[[1, 2, 3, 4], [5, 6, 7, 8], [9]]
final results = subLists
.map((l) => l.reduce((value, element) => value + element))
.toList();
print(results); //[10, 26, 9]
You can use this custom-made extension method to sum every n in a `List``, just add it inside your file outside your classes :
extension SumEveryExtension on List<num> {
List<num> sumEvery(int n) {
num nSumTracker = 0;
List<num> result = [];
for (int index = 0; index < length; index += 1) {
nSumTracker += this[index];
print("current" + nSumTracker.toString());
if ((index +1) % (n ) == 0 && index != 0) {
result.add(nSumTracker);
nSumTracker = 0;
}
}
return result;
}
}
And use it in your code like this:
List<int> list = [1, 2, 3, 4, 5, 6, 7, 8];
print(list.sumEvery(4)); // [10, 26]
You can also customize the n from the method to sum for any other n.

find only same value of that closest to the current index element in an array dart/flutter

I have an array that have same value, so i want to like filter it only for same value that closest to the current index, example :
A[0] = 2,
A[1] = -2,
A[2] = -2,
A[3] = 9,
A[4] = 9,
A[5] = 9,
A[6] = 4,
A[7] = -2,
A[8] = -2,
A[9] = -2,
i want my code can find that the index 1 2 is have same value which is -2 with length 2,
index 3 4 5 have same value 9 with length 3
and index 7 8 9 have same value -2 with length 3 and my code will return only the length of the most in the same value range and closest to index 0 which is value 9
void main() {
var nInt = <ArrayA>[
ArrayA(e: 'A', n: 2),
ArrayA(e: 'A', n: -2),
ArrayA(e: 'A', n: -2),
ArrayA(e: 'A', n: 9),
ArrayA(e: 'A', n: 9),
ArrayA(e: 'A', n: 9),
ArrayA(e: 'A', n: -1),
ArrayA(e: 'A', n: 7),
ArrayA(e: 'A', n: -2),
ArrayA(e: 'A', n: -2),
ArrayA(e: 'A', n: -2),
for (var i = 0; i < nInt.length; i++) {
for (var j = i + 1; j < nInt.length; j++) {
if (nInt[j].n == nInt[i].n) {
} else {
break;
}
}
];
class ArrayA {
final String e;
final int n;
ArrayA({this.e, this.n});
#override
String toString() {
return '$n';
}
}
In-order to achieve that, you need to store the comparison result and nearest index somewhere. For this purpose you can create a class like:
class Counter {
final int index;
final int number;
final int count;
Counter({required this.index, required this.number, required this.count});
#override
String toString() {
return '$count times $number at $index';
}
}
And change the logic to:
var counterValues = <Counter>[];
for (var i = 0; i < nInt.length; i++) {
int count = 1;
int value = nInt[i].n;
for (var j = i + 1; j < nInt.length; j++) {
if (nInt[j].n == nInt[i].n) {
count += 1;
} else {
// Break the inner loop and go to next outer-loop iteration
// You can optimise this by skipping already checked positions (ie: Update i)
break;
}
}
counterValues.add(Counter(index: i, count: count, number: value));
}
And finally to find the most recurring nearest value, you can use the reduce:
var result =
counterValues.reduce((a, b) => (a.count >= b.count && a.index < b.index) ? a : b);
print(result); // Output: 3 times 9 at 3

Whats the error in below code ? not getting expected output

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
object Solution {
def containsNearbyDuplicate(nums: Array[Int], k: Int): Boolean = {
for (i <- 0 until nums.length - 2) {
for (j <- i until nums.length - 1) {
if (nums(i) == nums(j) && (j - i == k)) return true
}
}
return false
}
}
Your input
[1,2,3,1]
3
Output
false
Expected
true
I don't think you're evaluating the full length of the inner list.
As written, j will never equal 3.
I think if you make your inner loop read for (j <- i until nums.length) that should work.
Probably want to fix the outer loop too. Otherwise, i will never reach the value of 3 stored in your array.
Using until will exclude, so if you use i <- 0 until nums.length -1 where length is 3, then the value of i will be 0, 1, 2 and end.
If you want to subtract - 1 because it feels easier or makes more sense to you, then you probably want to use i <- 0 to nums.length - 1.
Otherwise, i <-0 until nums.length will result in the value of i being 0, 1, 2, 3 as it iterates through the for loop.
Hope that helps.
This is functional, efficient as O(n) instead of O(n^2) and fixes a bug(i != j). You should always have a negative case too when testing ;)
import math.{min, max}
def containsNearbyDuplicate(nums: Array[Int])(k: Int): Boolean = {
val indexesToCheck = for {
i <- 0 until nums.length
j <- max(0, i - k) to min(nums.length - 1, i + k)
if i != j
} yield (i, j)
indexesToCheck.exists {case (i, j) => nums(i) == nums(j)}
}
containsNearbyDuplicate(nums = Array(1, 2, 3, 1, 5))(k = 3)
containsNearbyDuplicate(nums = Array(1, 2, 3, 1, 5))(k = 2)
containsNearbyDuplicate(nums = Array(1, 0, 1, 1, 5))(k = 1)

Product of Array Except Self with tail recursion

I would like to know if below function can be rewritten using tail recursion and using recursion in this case is any helpful in terms of time/space complexity?, below is what i have tried without tail recursion
input:[4,2,4,6]
output:[48,96,48,32]
def productExceptSelf(nums: Array[Int]): Array[Int]={
val len = nums.length
val output_arr= new Array[Int](len)
output_arr(0)=1
for(i<- 1 to len-1)
{
output_arr(i) = nums(i-1) * output_arr(i-1)
}
var R =1
var j=len-1
while(j>=0)
{
output_arr(j) = output_arr(j)* R
R = R * nums(j)
j-=1
}
output_arr
}
Solution without using division.
def productExceptSelf(nums: Array[Int]): Array[Int] =
Array.fill(nums.length)(nums)
.zipWithIndex
.map{case (ns,x) => ns.patch(x,Seq(),1).product}
Not sure how would you expect to write this using tail-recursion, but the simplest way would be something like this:
PS: I am using ArraySeq which is an immutable array (that was introduced on 2.13), feel free to keep using normal arrays.
def productExceptSelf(nums: ArraySeq[Int]): ArraySeq[Int] = {
val totalProduct = nums.product
nums.map(x => totalProduct / x)
}
Solution without using division.
def productExceptSelf(nums: ArraySew[Int]) : ArraySeq[Int] =
ArraySeq.tabulate(nums.length) { i =>
nums.foldLeft(1 -> 0) { case ((acc, j), x) =>
val newAcc = if (i == j) acc else acc * x
newAcc -> (j + 1)
}._1
}
Try this. It keeps track of the index and multiplies if the index of the current element isn't the same. However, it's not very idiomatic.
def productExceptSelf(nums: Array[Int]): Array[Int] =
productExceptSelf(nums, Array.fill(nums.size)(1), 0).toArray
def productExceptSelf(orig: Array[Int], res: Array[Int], i: Int): Array[Int] =
if (i == orig.size) res
else productExceptSelf(
orig,
res.zipWithIndex.map {
case (n, j) => if (j == i) n else n * orig(i)
},
i + 1
)
I like this one better:
def productExceptSelf(nums: Array[Int]): Array[Int] =
nums.indices.map {
i => nums.slice(0, i).product * nums.slice(i + 1, nums.size).product
}.toArray
You might prefer a view to do it lazily
def productExceptSelf(nums: Array[Int]) =
nums.indices.map {
i => nums.view.slice(0, i).product * nums.view.slice(i + 1, nums.size).product
}
# Starting from the right and recursing left, compute the right side product
# and pass it down. Upon reaching the left, compute the left side product,
# update the array, and bubble that value up.
def prod_not_self(arr, i, right):
if (i == 0):
left = 1
else:
left = arr[i-1] * prod_not_self(arr, i - 1, right * arr[i])
arr[i] = right * left
return left
if (__name__ == '__main__'):
arr = [1, 2, 3, 4]
print(arr)
prod_not_self(arr, len(arr) - 1, 1)
print(arr)
print()
arr = [-1, 1, 0, -3, 3]
print(arr)
prod_not_self(arr, len(arr) - 1, 1)
print(arr)

MaxSubArray using dynamic style

I have been trying to create code that counts the max substring from array and returns sum and starting and ending point. I have some error in there however that I cannot spot because for example when I use Array(-2, 1, -3, 4, -1, 2, 1, -5, 4) as source I get return (7, 5,8). However, the correct answer should be (6, 3, 6). Code below.
def solve(a: Array[Int]): (Int, Int, Int) = {
require(a.nonEmpty)
val n = a.length
val temp = Array.fill(n)(0, 0, 0)
var max = (0,0,0) // sum, start, end
for (i <- 0 to n-1) {
temp(i) = (a(i), i, i)
}
for (i <- 0 to n-1) {
for (j <- 0 to i) {
if (a(i) > a(j) && temp(i)._1 < temp (j)._1 + a(i)) {
temp(i) = (temp(j)._1 + a(i), j, i)
}
}
}
for (i <- 0 to n-1){
if (max._1 < temp(i)._1){
max = temp(i)
}
}
return max
}
How about a more Scala/functional approach?
def solve(a: Array[Int]): (Int, Int, Int) = {
a.tails.zipWithIndex.flatMap{
case (arr, ti) =>
arr.inits.map{
tail => (tail.sum, ti, ti + tail.length -1)
}
}.maxBy(_._1)
}
solve (Array(-2, 1, -3, 4, -1, 2, 1, -5, 4)) => res7: (Int, Int, Int) = (6,3,6)