A recurrence relation for the number of asterisks in the function - recurrence

I cannot get a recurrence for the number of asterisks printed by the function below, n is at least 2.
void Mystery(int n) {
if (n >= 2) {
print("**");
n=n-1;
Mystery(n);
n=n-1
Mystery(n);
print("***");
}
}
I have tried for n=2 case then I get **
Next, for n=3. Then for n=4. Then I tried to use induction method to get a general result for n. But I cannot reach any recurrence relation.

Here are some points to think about:
If n = 0 or n = 1, no asterisks are printed. Otherwise, exactly five asterisks are printed, plus those from the recursive calls.
The first recursive call made is to Mystery(n - 1), and the second is to Mystery(n - 2).

Related

How to `map` an `Iterable` partially in Dart?

Assuming I have a List as below:
final numbers = [1, 0, -1, 1, -3, 0];
I'd like to generate another list where 1 results in true and 0 results in false and skip the others. So, in other words, I'd like a method like map where I can also skip some elements. In terms of test, it would assert to:
expect(newList, equals([true, false, true, false]));
In this result, I'd like to skip -1 and -3 in the list.
How can I achieve this?
Environment
Dart 2.18.5
Use the .where() method to get a new iterable with only the elements satisfying a predicate, then use .map() to apply the transformation on the result.
final numbers = [1, 0, -1, 1, -3, 0];
final result = numbers.where((n) => n == 1 || n == 0).map((n) => n == 1);
print(result);
\\ (true, false, true, false)
The most direct version would be:
var result = numbers.expand<bool>((n) =>
n == 0
? const <bool>[false]
: n == 1
? const <bool>[true]
: const <bool>[]);
The expand method can do everything map and where can, plus more,
Not particularly efficient, but not all bad either.
Another approach is to use a sync* function:
var result = () sync* {
for (var number in numbers) {
if (number == 0) {
yield false;
} else if (number == 1) {
yield true;
}
}();
If you don't care about creating a list eagerly, that's a also the approach for a list literal:
var result = [for (var number in numbers)
if (number == 0) false else if (number == 1) true
];
Or:
const _map = {0: [false], 1: [true]};
var result = [for (var number in numbers} ...?_map[number]];
The options are endless. In practice, doing where and map is probably more readable.
Ariel's answer gave me a better idea. In the example of the question, what we'd like to filter out are two values, which are 1 and 0. The real problem I'm dealing with right now is more complicated than this one, it has a wide range of lookup list. I haven't specifically asked "What is a more programmatic way to do this?" or "What if the lookup list has more values?".
So, if the values I'm looking for are more than these two values, a List of lookup values and contains method would be better for my case.
final numbers = [1, 0, -1, 1, -3, 0];
final lookup = {1, 0};
final result = numbers.where((n) => lookup.contains(n)).map((n) => n == 1 ? true : false).toList();
print(result);
This has some drawbacks though, some of which that come to my mind are:
Performance is definitely worse than Ariel's answer. My solution uses contains, which will perform look-ups in lookup rather than a simple byte-comparison with n == 1. So, it isn't great with large lists.
hashCode must be overriden for non-primitives. It is easy to compare int with an int in this simple example, but if you have an instance, you need to override hashCode, otherwise Dart will compare the memory addresses rather than values.
Using another collection type for lookup other than Set might also have performance impact because Set is inherently O(1) while the others might depend on their standard library implementation, but it's safe to assume they're going to be worse than Set. (See Ariel's comment).
BTW, lookup does not have to be a Set. I've done it Set because lookup contains distinct values and the order is not important.
Iterable.map is a 1:1 mapping; if your input has n elements, then the output must have n elements too.
Using numbers.where(...).map(...) works, but alternatively:
Use Iterable.map first to map either to desired values or to an invalid sentinel value. If your sentinel value is null, then you can use Iterable.whereType to filter out them out:
var transformed = numbers.map((n) {
switch (n) {
case 0:
return false;
case 1:
return true;
default:
return null;
}
}).whereType<bool>();
You might prefer this if you want all of your logic in a single callback.
Use collection-for instead of Iterable.map and collection-if instead of Iterable.where:
var transformed = [
for (var n in numbers)
if (isValidValue(n))
transform(n),
];
where you define isValidValue and transform functions with your filtering and transformation logic respectively.

Extracting single value from returned pair

An external api call returns a pair of values:
('status', 'standby')
I thought it was possible to do an assignment like:
theQuery, theResponse = returnVal
So that the value I want (the second) ends up in theResponse, but this doesn't see to be working.
What I am really trying to test is whether theResponse = 'standby'
if theResponse=='standby' then …
A few solutions:
You can use unpack():
theQuery, theResponse = unpack(returnVal)
Alternatively, you do it "manually"
theQuery = returnVal[1]
theResponse = returnVal[2]
Or change your check to do
if returnVal[2]=='standby' then …
If your returnVal is a table with 2 values, there is no automatic unpacking in Lua, you cannot simply do theQuery, theResponse = returnVal
More explanation:
But quite related to this is that in Lua you can have a function returning multiple values, and its return values can be autumatlically unpacked, e.g.
function myfunc()
return 1,2
end
If you do a, b = myfunc() , a would be assigned 1 and b assigned 2
If you do just a = myfunc() a would be assigned 1 and 2 would be discarded.
Note that this is different from doing:
function myotherfunc()
return {1,2}
end
Here myotherfunc is returning a single value, which is a table containing 2 values.
If you now do a, b = myfunc() , a would be assigned the table {1,2} and b would be nil. There is no unpacking of the returned table.

I need explanation of method inject

I am trying to figure out how inject method works
Can someone explain this
def mysort
if djeca.any?
djeca.order(name: :asc).inject([]) { |sum, c| sum += c.mysort}.uniq
else
[self]
end
mysort is method of model class Books
In controller I call method mysort :
#mybooks= Books.find_by(name: 'renesansa')
#mybookss= #mybooks.leaf_wms
djeca.order(name: :asc).inject([]) { |sum, c| sum += c.mysort}.uniq
is equivalent to
sum = []
djeca.order(name: :asc).each{|c| sum = sum + c.mysort}
sum.uniq
Adding arrays is actually concatening, so your code just appends all the c.mysort into an array.
If I understand it correctly, you could also write :
djeca.order(name: :asc).map{|c| c.mysort}.flatten.uniq
Depending on your audience, you might want to write one or the other.
Note that you don't need to assign a value to sum in the inject block, it is done automatically.
(1..10).inject(0){|mem,i| mem += i}
#=> 55
(1..10).inject(0){|mem,i| mem + i}
#=> 55
You should follow this link https://samurails.com/tips/ruby-ruby-on-rails-inject/
For example:
result = [1,2,3,4].inject(0) { |sum, number| sum + number }
Here, the process starts from 0 index to the 3 index. First inject adds 1 & 2 to get the sum of two values and stored in sum variable(i.e. sum= 3) and then it takes the sum value and adds 3 to it, to get result(i.e sum=6) and so on. Finally you will get the result like 10.
djeca.order(name: :asc)
Retrieves array of active records
.inject([])
Looping through each active record. The initial output of inject is empty array [].
{ |sum, c| }
c - each active record
sum - Inject output value. Initially its []. On each iteration the value is appended to the array. (sum += [some values])

Getting aggregate ratio from a property from relationships with Cypher

Let's say I have a graph like this (excuse the pseudo-code):
(A)-[:RSVP {reply:true}]->(X)
(B)-[:RSVP {reply:true}]->(X)
(C)-[:RSVP {reply:false}]->(X)
How do I get the ratio of positive responses? I'm expecting a result that will give me the acceptance ratio of 0.66.
I mocked up your data this way:
CREATE (A), (B), (C), (X {label: "party time"})
MERGE (A)-[:RSVP {reply:true}]->(X)
MERGE (B)-[:RSVP {reply:true}]->(X)
MERGE (C)-[:RSVP {reply:false}]->(X);
Then, with this query, we can simply count the "yes's" and the "no's" separately, and create the ratio with simple division:
MATCH (X {label:"party time"})
MATCH (X)<-[:RSVP {reply:true}]-(yeses),
(X)<-[:RSVP {reply:false}]-(nos)
RETURN count(distinct(yeses))/count(distinct(nos));
The answer I get is 2, because there are 2 yeses and 1 no. (2/1 => 2)
Using #FrobberOfBits' sample data, the following is a more general query that takes care of a couple of special cases (which would otherwise cause Cypher to have a "/ by zero" error).
If are no RSVPs, the query returns the string "No Matches".
If are no false RSVPs, the query returns the string "Infinity".
Otherwise, the query returns the ratio of yeses to nos.
MATCH (X {label:"party time"})
OPTIONAL MATCH (X)<-[:RSVP {reply:true}]-(yes)
OPTIONAL MATCH (X)<-[:RSVP {reply:false}]-(no)
WITH LENGTH(COLLECT(DISTINCT yes)) AS yeses, LENGTH(COLLECT(DISTINCT no)) AS nos
RETURN CASE
WHEN yeses = 0 AND nos = 0 THEN "No Matches"
WHEN nos = 0 THEN "Infinity"
ELSE TOFLOAT(yeses)/nos
END;
To get the ratio that you originally asked for (ratio of yeses to the total number of responses), the query would be:
MATCH (X {label:"party time"})
OPTIONAL MATCH (X)<-[:RSVP {reply:true}]-(yes)
OPTIONAL MATCH (X)<-[:RSVP {reply:false}]-(no)
WITH LENGTH(COLLECT(DISTINCT yes)) AS yeses, LENGTH(COLLECT(DISTINCT no)) AS nos
RETURN CASE
WHEN yeses = 0 AND nos = 0 THEN "No Matches"
ELSE TOFLOAT(yeses)/(yeses + nos)
END;

Grails adding to a function's return values before returning them

I have a function (the caller) that returns certain values. Before they are returned, they are added to by the result of calling another function (the callee), is there a neater way to add the callee function's resultant values to the caller function's resultant values before the are returned?
def funcA() { // Caller Function
def a,b,c
a = blah
b = blah blah
...
def (d,e) = funcB()
a += d // Is there a neater way to encapsulate
b += e // these additions somehow into the previous line? maybe kind of like
// (a,b) += funcB() ?
return [a,b,c]
}
def funcB() { // Callee Function
def d,e
...
return [d,e]
}
to bad we don't have a zip, then something like [a,b].zip()*.sum() would work.
transpose() only gives you the pairs (not the remainder). so this only works, if your lists are the same length:
assert [43,668]==[[1,2,3],[42,666]].transpose()*.sum()
One could attempt to fill shorter list with zeros in this case, so the sum is not influenced (at that point this depends on the type there).
So this function is a workaround:
def zipadd(a,b) {
def l = [a,b]
// iterate over the size of the longer of the two lists
(0..(l*.size().max()-1)).collect{
// get the pairs, filter null, sum both
l*.getAt(it).findAll{it!=null}.sum()
}
}
assert [43,668,3]==zipadd([1,2,3],[42,666])
assert [43,668,3]==zipadd([42,666],[1,2,3])
assert [24,93,0,1]==zipadd([1,0,0,1], [23,93])
If you use pass l directly (a list of lists) instead of a and b this should also work with more than two elements.

Resources