Recursive call in a for yield structure in Scala [duplicate] - list

This question already has answers here:
N-queens in Scala
(1 answer)
Scala solution to nQueen using for-comprehension
(2 answers)
Passing a Set[List[Int]] typed value instead of List[Int] - why does that work?
(2 answers)
Closed 2 years ago.
I'm confused about the following Scala code from Coursera. The object of this code is to place n number of queens on a chest board so that no queens are threatened by each other, meaning same row, column or diagonal.
How does evaluation of the recursive call PlaceQueen(k-1) work in every step from when k =0 to k = n? Is there a recursive call PlaceQueen(k-1) happening in the line yield col::queens?
If col::queens appends columns of preceding rows as a list, the output of yield col::queens should be a list of columns. But how does it get transformed to a Set of list?
object nQueens extends App{
def queens(n: Int): Set[List[Int]] = {
def placeQueens(k: Int): Set[List[Int]] =
if (k == 0) Set(List())
else
for {
queens <- placeQueens(k - 1)
col <- 0 until n
if isSafe(col, queens)
} yield col :: queens
placeQueens(n)
}
def isSafe(col: Int, queens: List[Int]): Boolean = {
val row = queens.length
val queensWithRows = (row - 1 to 0 by -1) zip queens
queensWithRows forall {
case (c, r) => col != c && math.abs(col - c) != row - r
}
}
queens(4)
}
Output is:
Set(List(1,3,0,2), List(2,0,3,1))

This code has multiple infinite loops.
The queens method simple calls itself, which is clearly not correct:
def queens(n:Int):Set[List[Int]] = {
def placeQueens(k:Int):Set[List[Int]] = ???
def isSafe(col: Int, queens:List[Int]):Boolean = ???
queens(4)
}
The placeQueens method also calls itself after a bit of computation:
def placeQueens(k:Int):Set[List[Int]] = {
if (k==0) Set(List())
else
for {
queens <-placeQueens(k-1)
col <- 0 until n
if isSafe(col,queens)
} yield col:: queens
placeQueens(n)
}

Ignoring all the problems with the code which make it not doing what is intended, answers to your questions are:
how does it get transformed to a Set of list?
It gets transformed because first collection in the for is Set. It is set because Set is defined to be the return type of placeQueens.
queens <- placeQueens(k-1)
This also answers your first question:
Is there a recursive call placeQueen(k-1)?
as this is where the recursive call is.

Related

Minimum pluses required to make the equation (x = y) correct

Problem Statement:
Given an equation “x=y”, for example, “111=12”, you need to add pluses
inside x to make the equation correct. In our example “111=12”, we can
add one plus “11+1=12” and the equation becomes correct. You need to
find the minimum number of pluses to add to x to make the equation
correct. If there is no answer print -1.
Note that the value of y won’t exceed 5000. The numbers in the
corrected equation may contain arbitrary amounts of leading zeros.
Input Format The first line contains a string, A as described in the
problem statement.
Constraints 1 <= len(A) <= 10^3
I tried the recursive approach. Which is for every character in the 'x', I have two options I can include the plus sign next to the current digit or move to the next digit (by including the current digit with the next digit) I checked all the combinations and found the minimum pluses. As you know, this is exponential in complexity. I'm not able to apply dynamic programming for this problem as I can't think of the states for the dynamic programming.
I know this problem can be solved by dynamic programming. But, I don't know how to identify the state and the transition.
The first thing that comes to mind is to have a table
int f[N+1][M+1];
where N = len(x) and M = y. Then f[i][j] would record the solution to the sub-problem substr(x,0,i)=j; i.e. how many pluses are needed to get the sum j from the first i digits of x. The table can be incrementally updated through the recurrence relation:
f[i][j] = minimum over 0 <= k < i of (f[k][j - atoi(substr(x,k,i))] + 1)
Configurations that aren't obtainable or out-of-bounds should be understood as having f[i][j] == +infinity rather than -1.
The size of the table will be O(N*M) and the running time is O(N² M).
I'll leave the implementation details and the starting condition for you to complete.
Backtracking along with DP (Memoization) helped me to pass all the cases
here is my code. It passed all the cases in the given time limit
all_ans = {}
def min_pulses(A, target):
if (A, target) in all_ans:
return all_ans[(A, target)]
if len(A) == 0:
if target != 0:
return -1
else:
return 0
while len(A) > 0 and A[0] == '0':
A = A[1:]
if len(A) == 0 and target == 0:
return 1
if target < 0:
return -1
i = 1
ans = float('inf')# initializing ans to infinite number so that min can be update
while i <= 5 and i <=len(A):
curr_num = A[:i]
curr_ans = min_pulses(A[i:], target - int(curr_num))
if curr_ans >= 0:
ans = min(1 + curr_ans, ans)
i += 1
if ans == float('inf'):
ans = -1
all_ans[(A,target)] = ans
return ans
equation = input().split('=')
A = equation[0]
target = int(equation[1])
groups = min_pulses(A, target)
if groups < 0:
print(-1)
else:
print(groups - 1)
//import java.io.*;
import java.util.*;
//import java.lang.Math;
class NewClass15{
public static int minimum_pluses(String S)
{
StringBuilder s = new StringBuilder();
int target=0;
for(int i=0;i<S.length();i++) //distinguishing left and right strings respectively
{
if(S.charAt(i)=='=')
{
target=Integer.parseInt(S.substring(i+1,S.length()));
break;
}
s.append(S.charAt(i));
}
dp = new int[1000][5001][6];
int temp = dfs(s.toString(),0,0,target);
if(temp>=max)
return -1;
else
return temp;
}
static int dp[][][];
private static int dfs(String s,int len,int ind,int target)
{
if(target<0||len>5) return max;
if(ind==s.length())
{
int x=0;
if(len!=0)
x=Integer.parseInt(s.substring(ind-len,ind));
target-=x;
if(target==0) return 0;
return max;
}
if(dp[ind][target][len]!=0)
{
System.out.println("1 dfs("+ind+","+target+","+len+")");
return dp[ind][target][len]-1;
}
//add
long ans=max;
if(s.charAt(ind)=='0' && len==0)
{
System.out.println("2 dfs("+0+","+(ind+1)+","+target+")");
ans=Math.min(ans,dfs(s,0,ind+1,target));
return (int)(ans);
}
System.out.println("3 dfs("+(len+1)+","+(ind+1)+","+target+")");
ans=Math.min(ans,dfs(s,len+1,ind+1,target));
//add +
if(len!=0)
{
int x=Integer.parseInt(s.substring(ind-len,ind));
int j=ind;
while(j<s.length() && s.charAt(j)=='0') j++;
if(j!=s.length()) j=j+1;
System.out.println("4 dfs("+(1)+","+(j)+","+(target-x)+")");
ans=Math.min(ans,1+dfs(s,1,j,target-x));
}
System.out.println("final dfs("+ind+","+target+","+len+")");
dp[ind][target][len]=(int)(ans+1);
return (int)(ans);
}
static int max=10000;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String A;
A=scan.next();
int result;
result = minimum_pluses(A);
System.out.print(result);
}
}
This is the answer in java if it is of some help. I have not written the code though.
Can you provide me with some testcases for the given Minimum Pluses Question?
Thank you.
"""2nd one Answer"""
def permute(s):
result = [[s]]
for i in range(1, len(s)):
first = [s[:i]]
rest = s[i:]
for p in permute(rest):
result.append(first + p)
return [[int(j) for j in i] for i in result]
def problem(s):
x,y=s.split("=")
data=permute(x)
newdata=[]
for i in range(1,len(x)+1,1):
for j in data:
if i==len(j):
newdata.append(j)
for i in newdata:
if sum(i)==int(y):
print("str 1",i)
return
print("str -1")
def check_constraint(s):
if (not (1<=len(s)<=10^3)):
print(-1)
elif (s.split("=")[0]==s.split("=")[1]):
print(1)
elif (not (len(s.split("=")[0])>=len(s.split("=")[1]))):
print(-1)
else:
problem(s)
A=input()
check_constraint(A)

How can I write an efficient loop to solve this Code Wars problem?

The problem is the following:
This is a problem taken from code wars and titled 'Is my friend cheating?'
. A friend of mine takes a sequence of numbers from 1 to n (where n > 0).
. Within that sequence, he chooses two numbers, a and b.
. He says that the product of a and b should be equal to the sum of all numbers in the sequence, excluding a and b.
. Given a number n, could you tell the numbers he excluded from the sequence?
The function takes the parameter: n (n is always strictly greater than 0) and returns an array or a string of the form:
It happens that there are several possible (a, b). The function returns an empty array (or an empty string) if no possible numbers are found which will prove that my friend has not told the truth!
Example of returned sequence:
removNb(26) should return [(15, 21), (21, 15)]
I have tried a simple loop sequence:
def remov_nb(n):
somme = 0
liste = []
for num in range (n+1):
somme += num
for a in range(n+1):
for b in range(n+1):
if a * b == (somme-a-b):
liste.append((a,b))
return (liste)
and also used itertools:
def remov_nb(n):
from itertools import product
liste = []
somme = sum(x for x in range(1,n+1))
for x,y in product(range(1,n+1), range(1,n+1)):
if (somme - x - y) == (x * y):
liste.append((x,y))
return liste
The function doesn't work on Code Wars for lack of efficiency.
Can someone guide me here?

Unity - How to check if items within a list are the same value? [duplicate]

This question already has answers here:
C# Determine Duplicate in List [duplicate]
(11 answers)
Closed 2 years ago.
I have a list of type Vector3Int that contains the end location of my agents movement, I want to compare these values to see if they are equal,
pseudo code;
if (2 or more items within the list are the same value) {
create a new end of path location for one or more of the agents
}
Thanks in advance for you help
There are a few ways to do it.
You can run a loop that uses a LINQ query. It would check each item in the list and see if there are more than 1 of that item in the list. LINQ's version of Count() allows you to compare values.
bool HasDuplicates = false;
foreach (var item in MyList) {
if (MyList.Count(i => i.x == item.x && i.y == item.y) > 1) {
HasDuplicates = true;
break;
}
}
Or you can use Distinct() to make a second list that only has 1 of every value. Then compare the count of both lists. If the distinct one has a lower count, then there must be duplicates in the list.
var HasDuplicates = (MyList.Distinct().Count < MyList.Count)

Write a function that calculates the sum of all values in a list of integers that are both positive and even

The function should accept a single list as a parameter. The function should return an integer value as the result of calculation. If there are no positive and even integer values in the list, your function should return 0.
My current code:
def main():
print (sum_positive_even([1,2,3,4,5]))
print (sum_positive_even([-1,-2,-3,-4,-5]))
print (sum_positive_even([1,3,5,7,9]))
def sum_positive_even(list):
for num in list:
if num < 0:
list.remove(num)
for num in list:
if num % 2 == 1:
list.remove(num)
result = sum(list)
return result
main()
The output should be like:
6
0
0
I'm confused where I should put the 'return 0'.
Thanks TA!
Deleting from a list while you iterate over it is a Bad Idea - it's very easy to get hard-to-track-down bugs that way. Much better would be to build a new list of the items you want to keep. You don't need a special case of returning 0; the general approach should be able to handle that.
Also, it's better not to use list as a variable name in Python, because that's the name of a built-in.
A modification of your approach:
def sum_positive_even(lst):
to_keep = []
for num in lst:
if num > 0 and num % 2 == 0:
to_keep.append(num)
return sum(to_keep)
Since the sum of an empty list is 0, this covers the case where there are no positive even numbers.

Returning a Linear List in C++ and Time Complexity

I'm currently studying for my data structures exam and ran across a problem I could use clarification on. I'm supposed to create a function InsertZero(int k, int i) that inserts k zeroes after element i, checking indices each time and throwing appropriate exceptions.
I've done this, but I'm stuck on how to return a LinearList& that the function definition is asking me to in the class. I've tried return *element, return &element, and a few others to no avail. Where am I going wrong?
Additionally, I'm supposed to give the time complexity of the function as a "function of list length and k". I analyzed the steps throughout the function (see comments) and came up with O(k)...this doesn't use the list length, and I'm a bit confused on how to do so.
Any help will be greatly appreciated. I'm looking for comprehension, not just answers.
template <class T>
LinearList<T>& LinearList<T>::InsertZero(int i, int k)
{
//Complexity statements are in the form of
// "Number of steps" * "Number of times executed" = total
if ( i<0 || i> (MaxSize-1) || k<0) // 3 * 1 = 3
cout<<"Bad input exception thrown"<<endl;// 1 * 1 = 1
else if (k > (MaxSize-i-1) ) // 1 * 1 = 1
cout<<"NoMem exception thrown"<<endl; // 1 * 1 =1
else
{
while (k!=0) // 1 * k = k
{
element[i+1]=0; // 1 * k = k
i++; // 1 * k = k
k--; // 1 * k = k
}
return &element; // 1 * 1 = 1
}
//Total = 3+1+1+1+k+k+k+k+1 = 4k+7 = O(k)
}
I guess element array is a data member of the LinearList class. element is the basic C++ type (array of ints) whereas LinearList is derived one. I would do return *this at the end of your method.
The return type looks to be a the same type as the class. So you should return *this. It appears that elment should be a member variable, and that there is no need to return it.