divide and conquer – recursive equation of this code

power (x, n) {
if n == 0
back 1
if n is even
return power (x, n / 2) * power (x, n / 2)
if n is odd
return power (x, n / 2) * power (x, n / 2) * x

what will be the receipt for this code and how will you get a closed form using the substitution method

recursion – Constructs a recursive formula that is also a function on other parameters

I need to compute a recursive formula, but it is also a function on other parameters.

I've tried to follow the example to check:

fib[x_, y_, n_] := fib[x, y, n] = fib[x, y, n - 1] + fib[x, y, n - 2];
fib[x, y, 1] = fib[x, y, 2] = 1;

I did not help calculate

fib[1, 1, 3]

recursion – Recursive nesting with parameter

I would like to apply a function f recursively to an expression expr an arbitrary number of times. However, the problem is that f also takes a parameter i and I want it to change with each application. So once applied should look like f[1][expr].

Concretely, what I want, should look like this:

f[5][
   f[4][
      f[3][
         f[2][
            f[1][expr] ]]]]

It seems to me that it should be easy, but I do not know how to exploit functions like Nest, Do or Fold so that they produce this.

Convert recursive context-free grammars to left in strongly equivalent grammars without left recursion

It is a well-known problem that many top-down parsers have problems parsing a context-free grammar with left recursive rules. There are algorithms for converting grammars with direct direct or indirect direct recursive rules into equivalent grammars that do not have such rules.

For example, a simple recursive left grammar

$$ begin {alignat} {2}
& E && to E text {- V green V \
& V && to text {a} \ green text {b}
end {alignat}
$$

can be converted to a recursive equivalent right
$$ begin {alignat} {2}
& E && to V E & # 39; \
& E & # 39; && to text {& # 39; – & # 39;} V E & # 39; green varepsilon \
& V && to text {a} \ green text {b}
end {alignat}
$$

who accepts the same language.

The problem with this conversion is that the analysis trees of the same input string are fundamentally different. In the first case, the result is a left-oriented tree, reflecting the associativity to the left of the subtraction operator. On the other hand, the analysis tree of the second grammar would give a tree on the right, which makes it more difficult to process or evaluate the constructed analysis tree.

In terms of equivalence, this conversion produces a left non-recursive grammar weakly equivalent to the original, ie accept the same language, but not strongly equivalent. The latter also requires structurally equivalent analysis trees.

Is there a non-recursive version on the left, strongly equivalent and describing the same language for each grammar without left recursive context? If so, what would an algortihm that makes such a conversion look like?

vba – Recursive code to generate a parametric scan of input values

I generate a dataset based on each combination of entries. The input source range requires that the headers identify the parameters. In its current state, I am not happy because it is not as simple as I would like. Specifically, the module variables can be cleaned but I do not see how.

A simple example with 2 columns

---------------------
| Column1 | Column2 |
|---------|---------|
|    A    |    1    |
|    B    |    2    |
|    C    |    3    |
---------------------

generates

---------------------
| Column1 | Column2 |
|---------|---------|
|    A    |    1    |
|    A    |    2    |
|    A    |    3    |
|    B    |    1    |
|    B    |    2    |
|    B    |    3    |
|    C    |    1    |
|    C    |    2    |
|    C    |    3    |
---------------------

Addition of a 3-column entry table

-------------------------------
| Column1 | Column2 | Column3 |
|---------|---------|---------|
|    A    |    1    |   F1    |
|    B    |    2    |   F2    |
|    C    |    3    |   F3    |
|         |         |   F4    |
-------------------------------

generates

-------------------------------
| Column1 | Column2 | Column3 |
|---------|---------|---------|
|    A    |    1    |   F1    |
|    A    |    1    |   F2    |
|    A    |    1    |   F3    |
|    A    |    1    |   F4    |
|    A    |    2    |   F1    |
 . . . . . . . . . . . . . . .
|    C    |    2    |   F4    |
|    C    |    3    |   F1    |
|    C    |    3    |   F2    |
|    C    |    3    |   F3    |
|    C    |    3    |   F4    |
-------------------------------

etc.

The class module InputColumn is used to help compartmentalize the logic for each column and its corresponding maximum depth being equivalent to CountOfValues.

'@PredeclaredId
'@Folder("ParametricSweep.Model")
Option Explicit

Private Type THelper
    ColumnIndex As Long
    Values As Variant
    Identifier As String
End Type

Private this As THelper

Public Property Let Values(ByVal Value As Variant)
    this.Values = Value
End Property
Public Property Get Values() As Variant
    Values = this.Values
End Property

Public Property Get CountOfValues() As Long
    CountOfValues = UBound(Values) - LBound(Values) + 1
End Property

Public Property Let Identifier(ByVal Value As String)
    this.Identifier = Value
End Property
Public Property Get Identifier() As String
    Identifier = this.Identifier
End Property

Public Function Self() As InputColumn
    Set Self = Me
End Function

Public Function Create(ByVal ColumnIndex As Long, ByVal sourceArea As Range) As InputColumn
    Dim populatedCells As Range
    Set populatedCells = sourceArea.SpecialCells(XlCellType.xlCellTypeConstants)

    With New InputColumn
        .Identifier = populatedCells(1, 1).Value2
        .Values = Application.WorksheetFunction.Transpose(populatedCells.Offset(1).Resize(populatedCells.Rows.Count - 1).Value2)

        Set Create = .Self
    End With
End Function

The value scan is generated by informing the inputColumns() table and then enter PopulateArray 1 for the first level (the highest). After the call to PopulateArray it descends recursively from a deeper level up to fill the last column. At the return of each loop, the array is incremented recursionInputColumnPopulationIndex() which identifies which element should be populated for the corresponding recursion depth.

Option Explicit

Private parentArray() As Variant
Private inputColumns() As InputColumn
Private maxRecursionDepth As Long
Private recursionInputColumnPopulationIndex() As Long
Private populationRow As Long

Public Sub TestRecursive()
    Dim foo As Variant
    foo = RecursiveParametricSweep(Sheet1.Range("C5").CurrentRegion, True)

    Dim bar As Variant
    bar = RecursiveParametricSweep(Sheet1.Range("C16").CurrentRegion, False)
End Sub

Public Function RecursiveParametricSweep(ByVal inputSourceArea As Range, ByVal includeHeader As Boolean) As Variant
    maxRecursionDepth = inputSourceArea.Columns.Count

    ReDim inputColumns(1 To maxRecursionDepth)
    ReDim recursionInputColumnPopulationIndex(1 To maxRecursionDepth)

    PopulateInputColumns inputSourceArea

    Dim rowCount As Long
    rowCount = GetRowCount(inputColumns)
    If includeHeader Then
        ReDim parentArray(0 To rowCount, 1 To maxRecursionDepth)

        Dim headerRow As Long
        headerRow = LBound(parentArray)
        Dim headerColumn As Long
        For headerColumn = LBound(inputColumns) To UBound(inputColumns)
            parentArray(headerRow, headerColumn) = inputColumns(headerColumn).Identifier
        Next

        populationRow = LBound(parentArray) + 1
    Else
        ReDim parentArray(1 To rowCount, 1 To maxRecursionDepth)
        populationRow = LBound(parentArray)
    End If

    PopulateArray 1, includeHeader
    RecursiveParametricSweep = parentArray
End Function

Private Sub PopulateArray(ByVal recursionDepth As Long, ByVal includeHeader As Boolean)
    Dim populateElementCount As Long
    For populateElementCount = 1 To inputColumns(recursionDepth).CountOfValues
        If recursionDepth < maxRecursionDepth Then
            PopulateArray recursionDepth + 1, includeHeader

            recursionInputColumnPopulationIndex(recursionDepth) = recursionInputColumnPopulationIndex(recursionDepth) + 1
        Else
            Dim columnPopulationIndex As Long
            For columnPopulationIndex = recursionDepth To 1 Step -1
                parentArray(populationRow, columnPopulationIndex) = inputColumns(columnPopulationIndex).Values(recursionInputColumnPopulationIndex(columnPopulationIndex) + 1)
            Next

            recursionInputColumnPopulationIndex(recursionDepth) = recursionInputColumnPopulationIndex(recursionDepth) + 1
            populationRow = populationRow + 1
        End If
    Next
    recursionInputColumnPopulationIndex(recursionDepth) = 0
End Sub

Private Function GetRowCount(ByRef inputColumns() As InputColumn) As Long
    GetRowCount = 1
    Dim depthCounter As Long
    For depthCounter = LBound(inputColumns) To UBound(inputColumns)
        GetRowCount = GetRowCount * inputColumns(depthCounter).CountOfValues
    Next
End Function

Private Sub PopulateInputColumns(ByVal inputSourceArea As Range)
    Dim populateInputColumnsCounter As Long
    For populateInputColumnsCounter = LBound(inputColumns) To UBound(inputColumns)
        Set inputColumns(populateInputColumnsCounter) = InputColumn.Create(populateInputColumnsCounter, inputSourceArea.Columns(populateInputColumnsCounter))
    Next
End Sub
```

Recursion – What is an example of a recursive (simple) queue algorithm that does not use a helper function?

Here's an example facing you: write a function that takes two arguments a and b and returns the sum of the integers from 0 to amore b.

Here's another example: Write a function that returns the last element of a list or a special value if the list is empty.

let rec last l =
  match l with
  | () -> None
  | (x) -> Some x
  | h::t -> last t

Here is another example, in imperative language: apply a function to all elements of a list, in order, without returning a value.

let rec iter f l =
  match l with
  | () -> ()
  | h::t -> f h; iter f t

So, you can see that the recursive queue does not to have take an extra argument. However, taking an additional argument is a common pattern, and there is a deep reason for that.

A common reason for writing a recursive function is to traverse a recursive data structure. For example, the list data structure is defined recursively: a list is either the empty list ("nil") or a pair ("against") consisting of an element ("head") and a list ("tail"). In Ocaml syntax:

type list_of_foo = Foo_nil | Foo_cons foo * list_of_foo;; (* Foo_cons (head, tail) *)

To act on a list, you must specify what to do on the empty list and what to do on a non-empty list. To browse the entire list with a function, you make a recursive call to process the queue in the case of a non-empty list. A generic list path is called a fold. Writing a recursive function is a way of writing a crease; another way is to call a generic fold function and tell him what to do with nil and what to do with a counter (depending on the head and the result of the treatment of the tail of the list).

This is generalized to all recursive data structures. A peculiarity of the lists is that there is never more than one sub-list, so the call to process the queue can be a tail call. Contrast with a binary tree, for example:

type btree = Leaf of int | Node of btree * btree

To treat a btreewhen you reach a Nodeyou must treat both the first subtree (left child) and the second subtree (right child). They can not be both queue calls. But with lists, the recursive call can be a final call.

Integers do not look much like a data structure. But in reality, the recursion on an integer is usually based on the structure of integers. For example, when you recurse by enumerating integers from 0 to n or n to 0 (or 1 to n, etc.), you use the structure provided by Peano's axioms: an integer is either 0, or the successor of an integer.

So you have a recursive function that takes a data structure as an argument. It makes a recursive call based on a substructure of the original data. What is he returning? If the recursive call is a final call, what it returns should be the value returned in case the function does not make a recursive call. This is often the case "initial", for example 0 for a recurring function on an integer or the empty list for a recurring function on a list. What can you return in the case of departure? If you return a constant, it is not very interesting. If you want to return something that depends on the information collected from the data structure, you must pass this information through the final calls. And that's where the extra argument comes from. A tail-recursive function requires an additional argument (in addition to the data structure on which it is recursive) to collect data read from the data structure.

In the case of departure, you often want to return a constant. Therefore, you write a pair of functions: a recursive function with two arguments (the structure of data to browse and the accumulator), which returns the accumulator when it reaches the end of the data; and an auxiliary function just to give an initial value to the accumulator. This corresponds to the initial value argument for fold functions.

beginner – Recursive Merge Sort Algorithm (Python)

Merge sort

The merge sort algorithm is a general-purpose comparison-based sort algorithm.
Most implementations produce a stable sort in which the order of equal elements is preserved.


Just to exercise, I've implemented the merge sorting algorithm, reproduced below, and I would appreciate if you would consider any part of it to take into account the changes / / improvements, big or small.

Code

from typing import List, TypeVar
import random
from scipy import stats

T = TypeVar("T")


def recursive_merge_sort(input_list: List(T)) -> List(T):
    """
    Recursive Merge Sort
    -----------------------------------------------
    Merge Sort is a Divide and Conquer algorithm.
    It divides the input array in two halves,
    calls itself for the two halves and then merges the two sorted halves.
    The merge function is used for merging two halves.

    Attributes:
    - Time Complexity: O(N*Log N)
    - Space Complexity: O(N)
    - Stable Sort
    """

    # Assigns the length of input list.
    size_of_input_list = len(input_list)

    # Creates a new list for sorted output list.
    temp_output_list = (None) * size_of_input_list

    # Sorts the input list.
    recursive_sort(input_list, temp_output_list, 0, size_of_input_list - 1)

    return temp_output_list


def recursive_sort(input_list: List(T), temp_output_list: List(T), first_index: int, last_index: int) -> List(T):
    """
    This method recursively sorts the divided sublists
    """

    # Stops the recursion if there is only one element in the sublists.
    if first_index == last_index:
        return

    # Otherwise, calculates the middle point.
    mid_index = (first_index + last_index) // 2

    # Then, calls the two sublists recursively.
    recursive_sort(input_list, temp_output_list, first_index, mid_index)
    recursive_sort(input_list, temp_output_list, mid_index + 1, last_index)

    # Merges the two sublists.
    merge_sublists(input_list, temp_output_list, first_index,
                   mid_index, mid_index + 1, last_index)

    # Copies the sorted part into the temp_output_list.
    copy_list(input_list, temp_output_list, first_index, last_index)


def merge_sublists(input_list: List(T), temp_output_list: List(T),
                   first_start_index: int, first_end_index: int,
                   second_start_index: int, second_end_index: int) -> List(T):
    """
        This method merges the two sorted sublists with three simple loops:
        - If both sublists 1 and 2 have elements to be placed in the output merged list
        - If sublists 1 has some elements left to be placed in the output merged list
        - If sublists 2 has some elements left to be placed in the output merged list

        e.g., sublist 1 (1, 3, 5, 7, 9)
        e.g., sublist 2 (2, 4, 6, 8, 10, 12, 14)

        - First while loop generates: (1, 2, 3, 4, 5, 6 , 7, 8, 9, 10)
        - Second while loop just passes, since no elements left from the first sublist.
        - Third while loop generates: (1, 2, 3, 4, 5, 6 , 7, 8, 9, 10, 12, 14)

    """
    i = first_start_index
    j = second_start_index
    k = first_start_index

    while i <= first_end_index and j <= second_end_index:
        if input_list(i) <= input_list(j):
            temp_output_list(k) = input_list(i)
            i += 1
        else:
            temp_output_list(k) = input_list(j)
            j += 1

        k += 1

    while i <= first_end_index:
        temp_output_list(k) = input_list(i)
        i += 1
        k += 1

    while j <= second_end_index:
        temp_output_list(k) = input_list(j)
        j += 1
        k += 1


def copy_list(input_list: List(T), temp_output_list: List(T), first_index: int, end_index: int) -> List(T):
    for i in range(first_index, end_index+1):
        input_list(i) = temp_output_list(i)


if __name__ == "__main__":

    # Creates a dash line string and a new line for in between the tests.
    delimiter = "-" * 70 + "n"

    # Generates a random integer list.
    TEST_LIST_INTEGER = random.sample(range(-100, 100), 15) * 3
    print(f"""The unsorted integer array is:
        {TEST_LIST_INTEGER}""")
    print(delimiter)

    # Generates a random float list.
    TEST_LIST_FLOAT = stats.uniform(0, 100).rvs(45)
    print(f"""The unsorted float array is:
        {TEST_LIST_FLOAT}""")
    print(delimiter)

    # Sample float/integer test list for input.
    INTEGER_FLOAT_INPUT = list(TEST_LIST_INTEGER + TEST_LIST_FLOAT)

    # Sample float/integer test list for output.
    INTEGER_FLOAT_OUTPUT = sorted(INTEGER_FLOAT_INPUT)

    sorting_algorithms = (
        ("Recursive Merge Sort", recursive_merge_sort)
    )

    # Testing
    for description, func in sorting_algorithms:
        if (func(INTEGER_FLOAT_INPUT.copy()) == INTEGER_FLOAT_OUTPUT):
            print(f"{description} Test was Successful.")
        else:
            print(f"{description} Test was not Successful.")
        print(f"""{description} (Integer):
            {func(TEST_LIST_INTEGER.copy())}""")
        print(f"""{description} (Float):
            {func(TEST_LIST_FLOAT.copy())}""")
        print(delimiter)

References

widget – UX Confusing report parameter for recursive

I've been responsible for implementing a report parameter containing other report parameters, for a reporting software I'm working on. The user interface, as described to me, is really confusing, but I am unable to design a better design. It's like something like this: enter the description of the image here and should behave as follows:

  • When you click on it, the child report parameter must be filled in on the left. If this child report parameter has report parameters, it must replace the left-hand content when its content is selected, and its child parameter should appear on the right, with the parent just above it, as follows:
    • enter the description of the image here
  • The user should be able to go back to the parent / principal level
  • When the user enters values ​​for the child settings, the main check box should be checked
  • When the user checks the box, the default parameter values ​​for all levels must be set.

All this had to be under a the requirement for the widget has been removed (literally impossible, and even if it was not the case, it's paradoxical like hell), but even after that, this design is really confusing. The checkboxes should not switch to the buttons in the list in which they are located, this is counterintuitive. However, I have a hard time finding something better. Could you help me?

An idea that I have

Instead of having to check the box to indicate if a company is included in the default values, just click the button to solve the problem. To deselect this company, the user must see a trash icon or an X to delete, or even a small Discard button next to the active list button.

The weakness of this approach is that what happens if the user has several companies selected and only wants to change the child settings from one of them?

computer architecture – How can a non-primitive recursive function such as the Ackermann function be implemented on hardware?

Thanks for contributing an answer to Computer Science Stack Exchange!

  • Please make sure to respond to the question. Provide details and share your research!

But to avoid

  • Ask for help, clarification, or answer other answers.
  • Make statements based on the opinion; save them with references or personal experience.

Use MathJax to format equations. MathJax reference.

To learn more, read our tips for writing good answers.

How to prove the performance, Big Omega, of building a binary heap using the recursive method is Ω (nlog (n))

We can learn the big-O of building a binary heap using the recursive method is O (n log n) from the wiki
"This approach, known as Williams' method after the inventor of the binary heaps, is easily executable in a time O (n log n): it performs n insertions at a cost in O (log n). A) "We can also know if we are building the heap using other methods. the big O could be better. Where should we start if we want to prove that the performance, Big Omega, of building a binary heap using the recursive method is Ω (nlog (n)), which is identical to Big -O?