performance – Recursively unpacking a javascript object

I’m seeing a React course and we where studying fundamentals of javascript for a while. We saw how to access the content of an object and display it in console. My solution for the problem of displaying an unknown object was the following:

``````function unpackObject(obj, tabs = '') {
const props = Object.getOwnPropertyNames(obj);

let v;
props.forEach(p => {
v = obj(p);
//v = Object.getOwnPropertyDescriptor(obj, p).value; | side question: is it better?

if (v instanceof Object) {
console.log(`\${tabs}\${p} \${Object.prototype.toString.call(v)}`);
if (v instanceof Array)
v.forEach((x, i) => console.log(`\${tabs}t(\${i}): \${x}`));
else
unpackObject(v, `\${tabs}t`);
} else
console.log(`\${tabs}\${p}: \${v}`);
});
}
``````

Which I tested using the following code.

``````const testObject = {
name: 'Miguel',
surname: 'Avila',
age: undefined, //LOL
marital_status: 'Single',
hobbies: ('Write Code', 'Watch YT Videos', 'etc. idk'),
contact: {
phones: ('xxxxxxxxxx', 'xxxxxxxxxx'),
}
};

unpackObject(testObject);
``````

My questions are: Can this code be faster and/or shorter? Are there any tricks capable of improving it for massive objects? (I mean, I fear recursion because when it goes wrong it’s a big deal).

algorithms – Making use of one function to recursively find n/3 of another

If $$n/3$$ is equal to the index of the current median, the algorithm terminates.

If $$n/3$$ is greater than the index of the current median, the algorithm moves to the right subarray and recursively solves there.

If $$n/3$$ is smaller than the index of the current median, the algorithm moves to the left subarray and recursively solves there.

Time Complexity:

For a subarray of size $$t$$, finding the median, left subarray, right subarray, take $$O(t)$$ time. Since, the subarray is getting halved in every iteration, the total running time is: $$O(n) + O(n/2) + O(n/4) + dotsc + 1 = O(n)$$

equation solving – Show that all coefficients in a recursively defined function are integers

Problem 2 in the 2017 Putnam exam is:

Let $$Q_0(x) = 1$$, $$Q_1(x) = x$$, and $$Q_n(x) = frac{Q_{n-1}^2(x) – 1}{Q_{n-2}(x)}$$.

Show that $$Q_n(x) in mathbb{Z}(x) forall n geq 0$$.

(Recall that $$mathbb{Z}(x)$$ denotes the set of all polynomials in $$x$$ with integer coefficients.)

We can define the function recursively:

``````q(0, x) = 1;
q(1, x) = x;
q(n_Integer, x_) := (q(n - 1, x)^2 - 1)/q(n - 2, x);
``````

We can confirm that the first 10 (or indeed any number) of terms contains only integer-valued coefficients by:

``````IntegerQ /@
DeleteDuplicates(
Flatten(CoefficientList(
FullSimplify@Table(q(i, x), {i, 0, 10}),
x)))
``````

However, we want to prove the relation for all $$n$$.

We can follow the steps in the linked video, but that does not exploit Mathematica‘s simplification or other functionality. I’ve tried to use functionality to isolate `q(n,x)` in terms of `q(n-1,x)` and `q(n-2,x)` and then argue that because $$Q_0(x)$$ and $$Q_1(x)$$ are both in $$mathbb{Z}(x)$$ then so are $$Q_n(x)$$ for all $$n geq 2$$, but have found no clever way other than (essentially) performing the algebra “by hand.”

Any suggestions on an elegant, computational approach?

sorting – Using JavaScript, given a JSON value, recursively find all JSON objects, then sort keys in-place

Some background: JavaScript is not my primary language, so I’m looking to get some constructive criticism here.

I built a tiny single page HTML app that pretty prints JSON text. It’s very useful when I am looking a process logs that dump JSON without pretty printing.

In my tool, I added a checkbox to optionally sort the keys for all JSON objects.

To be clear, I am only targetting the most modern browsers, so please assume the latest and greatest of JavaScript is available.

``````function _sort_keys_deeply(json_thing)
{
if (false === _is_sortable(json_thing))
{
return json_thing;
}
if (Array.isArray(json_thing))
{
for (var i = 0; i < json_thing.length; ++i)
{
const val = json_thing(i);
if (_is_sortable(val))
{
const val2 = _sort_keys_deeply(val);
json_thing(i) = val2;
}
}
return json_thing;
}
// else: object
const sorted_obj = _sort_object_keys(json_thing);
const key_arr = Object.keys(sorted_obj);
for (var i = 0; i < key_arr.length; ++i)
{
const key = key_arr(i);
const val = sorted_obj(key);
if (_is_sortable(val))
{
const val2 = _sort_keys_deeply(val);
sorted_obj(key) = val2;
}
}
return sorted_obj;
}
function _is_sortable(z)
{
// Beware: null is type object, but is not sortable.
const x = (null !== z) && ('object' === typeof(z) || Array.isArray(z));
return x;
}
// Ref: https://stackoverflow.com/a/31102605/257299
function _sort_object_keys(obj)
{
const key_arr = Object.keys(obj);
// In-place array sort
key_arr.sort();
// Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
const f =
function(new_obj2, key/*, index, array*/)
{
new_obj2(key) = obj(key);
return new_obj2;
};
const new_obj = {};
key_arr.reduce(f, new_obj);
return new_obj;
}
``````

macos – Copy directory recursively without copying the file contents

macos – Copy directory recursively without copying the file contents – Ask Different

gr.group theory – Is the verbal subgroup of a recursively presented set, recursively presented

The concrete answer that I would like to ask is as follows:
Take a set of finite words $$W$$ and suppose that $$R$$ is a finite set on the free group in n letters. Construct $$W(R)$$, the verbal subgroup associated to $$R$$. (https://en.wikipedia.org/wiki/Verbal_subgroup).

Is it true that $$W(R)$$ is recursively enumerable?

Thank you very much in advice.

How do we prove that the set of diophantine equations having integer solutions is recursively enumerable? Thanks a lot.

Information of recursively enumerable sets
https://en.wikipedia.org/wiki/Recursively_enumerable_language
Information of Diophantine equation
https://en.wikipedia.org/wiki/Diophantine_equation

recursion – Find Optimal Permutations Recursively in Java

I’m asking for your feedback on my code. My specific concern is the simplicity of my implementation. My code is correct and the performance is ok, but I feel like that there must be an easier way to solve this. If you find any problems besides simplicity, I’ll be happy if you point them out as well. Please be aware that I’m looking only for recursive solutions.

Description of the problem

The task is to find a recursive (not iterative!) solution to the following problem:

A list of tokens can be arranged in different ways, for example (r,r,r,b,b,w,w) can be arranged as:

1: bwrbwrr

2: rbrwrbw

3: rbrwbrw

4: rbwrbwr

The quality of any arrangement is a tuple (“minimal distance between same tokens”, “times minimal distance occurs”). The quality is sorted in ascending order first by “minimal distance” and only if “minimal distance” is equal, the quality is sorted in descending order by “number minimal distance occurs”. In the given example we get the following scores:

1: (0,1) // minimal distance between tokens of r is 0. The minimal distance occurs once.

2: (1,2) // minimal distance between tokens of r is 1, occurs twice.

3: (1,1) // minimal distance between tokens of r is 1, occurs once.

4: (2,4) // minimal distance between tokens of r, b and w resp. is 2, occurs 4 times.

Therefore, 4 has the highest quality, followed by 3 and so on.

The task is to find arrangements with the highest possible scores for a given input list!

My Solution in Java

``````import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.HashSet;

public class Combinations {

private int minimumDistance;
private int countDistance;

/**
* {@summary} Finds all optimal permutations and returns them.
* @param arr The list of Characters to be permuted.
*/
public List<List<Character>> findOptimalPermutation(ArrayList<Character> arr) {

for (int i=arr.size()-1; i>=0 ;i--) {
minimumDistance = i;

for (int j=0; j<arr.size(); j++) {
countDistance = j;
if (permute(arr,0).size()!=0) {break;}
}

if (permute(arr,0).size()!=0) {break;};
}
return permute(arr,0);

}

/**
* {@summary} Finds permutations depending on the value of maxMinDistance and countDistance.
*
* @param arr
* @param k
*/

private List<List<Character>> permute(ArrayList<Character> arr, int k){

HashSet<Character> index = new HashSet<>();
ArrayList<ArrayList<Character>> arrs = new ArrayList<>();
for(int i = k; i < arr.size(); i++){
java.util.Collections.swap(arr, i, k);
if (!index.contains(arr.get(k))) {
}
java.util.Collections.swap(arr, k, i);
}

List<List<Character>> solutions = new ArrayList<>();
for (ArrayList<Character> unique_arr : arrs) {
boolean minDistanceBiggerThan = findMinimumDistance(arr,k-1)>=minimumDistance;
if (k>0 && minDistanceBiggerThan) {
} else if (k==0) {
}
}

if (k == arr.size() -1) {
boolean minDistanceBiggerThan = findMinimumDistance(arr, k)>=minimumDistance;
boolean minDistanceOccursLessThan = countMinimumDistance(arr,minimumDistance)<=countDistance;
if (minDistanceBiggerThan && minDistanceOccursLessThan) {
}
}
return solutions;
}

/**
* {@summary} Finds the minimal distance between all pairs of identical elements.
* @param arr
* @param k
* @return min
*/
private int findMinimumDistance(List<Character> arr, int k) {
HashMap<Character, Integer> map = new HashMap<>();
int min = 99999;
for (int i=0; i<=k ;i++) {
if (map.containsKey(arr.get(i))) {
if (i - map.get(arr.get(i)) - 1 < min) {
min = i - map.get(arr.get(i)) - 1;
}
map.put(arr.get(i), i);
} else {
map.put(arr.get(i), i);
}
}
return min;
}

/**
* {@summary} Counts how often the minimal distance occurs.
* @param arr
* @param min
* @return count
*/
private int countMinimumDistance(List<Character> arr, int min) {
HashMap<Character, Integer> map = new HashMap<>();
int count = 0;
for (int i=0; i<arr.size(); i++) {
if (!map.containsKey(arr.get(i))) {
map.put(arr.get(i), i);
} else {
if (i - map.get(arr.get(i)) - 1 == min) {
count++;
}
map.put(arr.get(i), i);
}
}
return count;
}

public int getMaxMinDistance() {
return minimumDistance;
}

public int getCountDistance() {
return countDistance;
}

}
``````

Execution in Main:

``````import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {

public static void main(String() args) {

ArrayList<Character> arr = new ArrayList<Character>(Arrays.asList('r','r','r','r',
'b','b','b',
'g','g',
'w','w','w','w',
's','s'));

Combinations combinations = new Combinations();
List<List<Character>> optimalVals = combinations.findOptimalPermutation(arr);
System.out.println("All possible lists of tokens: ");
System.out.println(optimalVals);
System.out.println();
int maxMinDistance = combinations.getMaxMinDistance();
int countDistance = combinations.getCountDistance();
System.out.printf("The number of possible is solutions is: %d. These solutions have the following score:n", optimalVals.size());
System.out.printf("Minimal Distance: %d, Frequency count of minimal distance: %dn", maxMinDistance, countDistance);
System.out.println();

}
}
``````

Output:

``````All possible lists of tokens:
((r, w, b, g, r, w, s, b, g, r, w, s, b, r, w), (r, w, b, g, r, w, s, b, r, g, w, s, b, r, w), (r, w, b, g, r, w, s, b, r, w, g, s, b, r, w), (r, w, b, g, r, s, w, b, g, r, w, s, b, r, w), (r, w, b, g, r, s, w, b, r, g, w, s, b, r, w), (r, w, b, g, s, r, w, b, g, r, w, s, b, r, w), (r, w, b, s, r, g, w, b, r, s, w, g, b, r, w), (r, w, b, s, r, g, w, b, s, r, w, g, b, r, w), (r, w, b, s, r, w, g, b, r, w, s, g, b, r, w), (r, w, b, s, r, w, g, b, r, s, w, g, b, r, w), (r, w, b, s, r, w, g, b, s, r, w, g, b, r, w), (r, w, b, s, g, r, w, b, s, r, w, g, b, r, w), (w, r, b, g, w, r, s, b, g, w, r, s, b, w, r), (w, r, b, g, w, r, s, b, w, r, g, s, b, w, r), (w, r, b, g, w, r, s, b, w, g, r, s, b, w, r), (w, r, b, g, w, s, r, b, g, w, r, s, b, w, r), (w, r, b, g, w, s, r, b, w, g, r, s, b, w, r), (w, r, b, g, s, w, r, b, g, w, r, s, b, w, r), (w, r, b, s, g, w, r, b, s, w, r, g, b, w, r), (w, r, b, s, w, g, r, b, w, s, r, g, b, w, r), (w, r, b, s, w, g, r, b, s, w, r, g, b, w, r), (w, r, b, s, w, r, g, b, w, r, s, g, b, w, r), (w, r, b, s, w, r, g, b, w, s, r, g, b, w, r), (w, r, b, s, w, r, g, b, s, w, r, g, b, w, r))

The number of possible is solutions is: 24. These solutions have the following score:
Minimal Distance: 3, Frequency count of minimal distance: 4
``````

python – How to refactor an imperative function recursively?

I have an HL7 MLLP message building class I’d like to refactor. The way HL7 over MLLP works is there are multiple fields, usually delimited by the `|` character. Within the field, there can be lists, delimited by `^`, and within those lists there can be lists, delimited by `&`.

So for example, the following structure:

``````message = ('foo',
('bar', 'baz',
('a', 'b', 'c')
),
'comment')
``````

will be serialized to the message:

`serialized = "foo|bar^bar^a&b&c|comment"`

I’ve written a simple class whose constructor arguments indicate where in the list of fields you want to place some data, as well as the data itself. The `__repr__` method is defined for easy use of these objects in f-strings.

This is the class:

``````class SegmentBuilder:
def __init__(self, segment_type, *args):
if not isinstance(segment_type, str):
raise ValueError("Segment type must be a string")
self.state = {0: segment_type}
for index, value in args:
self.state(index) = value
self.fields = (None for _ in range(1 + max(self.state.keys())))

def __repr__(self):
# Do a Depth-first string construction
# Join first list using ^, second list using &
# This is ugly, but will work for now
# Could do better with an actual recursive depth-based approach
def clean(obj):
return str(obj) if obj is not None else ''
for index, value in self.state.items():
if not isinstance(value, list):
self.fields(index) = value
else:
subfields = ()
for subfield in value:
if not isinstance(subfield, list):
subfields.append(clean(subfield))
else:
subsubfields = ()
for subsubfield in subfield:
subsubfields.append(clean(subsubfield))
subfields.append('&'.join(subsubfields))
self.fields(index) = '^'.join(subfields)

return '|'.join((clean(field) for field in self.fields))
``````

Now, there’s clearly a recursive refactoring trying to leap out of this, probably involving some list comprehension as well. I thought it might involve passing an iterator based on the sequence of delimiter characters, eg `"|^&"`, but the base case had me confused (since you would have to catch `StopIteration`, and then maybe signal to the caller via returning None?). Any guidance on this recursive refactor would be very helpful!

recursion – C delete object, recursively if directory

This is my function that uses recursion to recursively delete a directory. I like my way of skipping entries `.` and `..`. But should I be casting the name lengths to `unsigned int` because I am quite sure there will not be file paths longer than 4 gigacharacters? Or is storing the result of `strlen` in any type other than `size_t` bad practice? Any other comments here? Also is using VLAs in a recursive function risky, could it cause a stack overflow error? Is the VLA OK, or should I just use `malloc()` (I vehemently refuse to simply use a fixed size buffer that should be big enough, like `char Entry(1024)`)?

``````int Remove(const char *const Object) {
DIR *const Dir = opendir(Object);
if (Dir) {
struct dirent *Dirent;
const unsigned int Len = (unsigned int)strlen(Object);
const char *const Name = Dirent->d_name;
const unsigned int NameLen = (unsigned int)strlen(Name);
if (Name(0) == '.' && (NameLen == 1 || (Name(1) == '.' && NameLen == 2))) {
continue;
}
char Entry(Len+NameLen+2), *const CurrPtr = memcpy(Entry, Object, Len)+Len;
*CurrPtr = '/';
*(char *)(memcpy(CurrPtr+1, Name, NameLen)+NameLen) = 0;
if ((Dirent->d_type == DT_DIR? Remove : remove)(Entry)) {
return -1;
}
}
if (closedir(Dir)) {
return -1;
}
}
return remove(Object);
}
``````