Best Logic to implement comparison of two arrays
I have two arrays arr 1 and arr 2, here both the arrays will have some common items and many uncommon items, first the common items should be removed from both the arrays.
therefore for each uncommon item in arr 1 may probably be a sum of two or more values in arr 2 or vice versa.if the sum is found the values must be removed from the respective arrays. Finally the output should only be the unmatched values on both the arrays
I need a logic where i can do this calculation in much faster way.
1 answer

I'm not going to give out the code that implements your logic but rather I would be happy to point you in the right direction.
I code in C++, so I'm gonna answer with respect to that. If you want a different language, I'm sure you can freely do so.
To remove the common elements:
You first sort the arrays
arr1
andarr2
. Then do a set_symmetric_difference on them. This will effectively run in linear time. Then create two sets out of them, sayset1
andset2
.To remove pairs that sum up to an element in the other array
For this, you need to loop through all the possible pairs of elements in
arr1
and check if this sum of this pair exists inset2
. Likewise do forarr2
as well and remove the element when necessary.This can be done in O(n^{2}). If you don't want to create the extra sets, you can always trade performance for memory, by just looping through the pairs of
arr1
and checking for the sum in thearr2
by doing a binary search. Then the time complexity may shoot up to O(n^{2} log(n)).
See also questions close to this topic

Should this function be ran asynchronously on the server
im not that experienced with node js but im developing something similar to how uber displays their cars in real time on a map.
So i have an sql database with a ton of cars and their gps location. The client sends their gps coordinates and a radius to the following function. some is in pseudo code for now.
var mysql = require('mysql'); var express = require('express'); var connection = mysql.createConnection({ host: "", port: , user: "", password: "", database: "" }); user.on('returnCars', function(gps, radius){ connection.query({ sql: "SELECT * FROM cars WHERE radius = ?", values: [username] }, function(error, results, fields) { if(results) { user.emit('returnCars', results); } } }); }); });
So as sql querys arnt instant, if there was 1000 people running this function at once it would surely clog up. All my research is telling me that this is the right way to do it so the only option would for it to be ran asnync right?
Also would it just be the returnCars function to run asynchronously? Im not sure if because the connection/ sql details variable isnt in a function or anything it would all try and read it at once so maybe it should go inside the function or something.

Error when trying to print a private static integer from class. C++
I am having a problem with my code. Everytime I try to print my private static int total from the DivSales class, the program runs however it prints "00007FF768191492" Can someone please tell me what I've done wrong in my code? I am using C++ in Visual Studios. Keep in note that also I tried to print out DivSales::totalSale; in the main function however I got a similar output(the program runs) that says "00007FF726FF1492". Thank you for helping me.
#include <iostream> #include <string> #include <iomanip> #include <Windows.h> using namespace std; class DivSales { private: static int total; public: int qArr[4]; // here is the declared array I input the 4 integers static int totalSale() { return total; // here is the function to return total. } void fourSale(int first, int second, int third, int fourth) //these integers are inputted by user. { if (valid(first) == true) //this and below is an example of how I am adding to the total variable. Imagine 3 more of these. { qArr[0] = first; total += first; } } int DivSales::total = 0; int main() { DivSales div1; //here i declare an object. I have 5 more but I will display two for example purposes. div1.fourSale(6543, 3000, 4000, 5000); // here i input the 4 integers cout << div1.totalSale << endl << endl; // here I try to print out the total however it prints the error I was talking about. }

How does python decide AND and OR?
So, python skips the logic and just returns the value that decided the operation when using and and or. For example:
>>> 1 and 2 2 >>> 1 or 2 1
So Python seems to be deciding based on size of value in this case. However, this doesn't always make sense, at least not directly. Does Python decide this value based on the objects id somehow? Or, I'm not sure here, but perhps off the repr() method? How is python making this decision?

Solve a simple packing combination with dependencies
This is not a homework question, but something that came up from a project I am working on. The picture above is a packing configuration of a set of boxes, where A,B,C,D is on the first layer and E,F,G on the second layer. The question is that if the boxes are given in a random order, what is the probability that the boxes can be placed in the given configuration?
The only condition for the placement is all the boxes need to be placed from top down and cannot be moved once placed. Therefore no sliding under the existing box or floating placement is allowed, but it's okay to save room for the box on the same layer. For example, E can only be placed when A and B are already in place. If the handing order is AEB... then it cannot be placed in the specified configuration, if the handing sequence is ACBE... then E can be correctly placed.
A more formulated description is to translate the packing configuration to a set of dependencies, or prerequisites. ABCD on the first layer has 0 dependencies, while dependencies of E are {A and B}, F are {B and C}, and G are {C and D}, the corresponding dependencies must happen before E or F or G happens. Also while it doesn't apply to this problem, in some problem the dependencies could also be of a "or" relationship instead of "and".
I wonder what are the general deterministic algorithms to solve this, or this class of problem? A way I could think of is generating A,B,C,D,E,F,G in random order for 10,000 times and for each order check if the corresponding prerequisites have happened when each element is called. This naive idea, however, is time consuming and cannot produce the exact probability(I believe the answer to this problem is ~1/18 based on this naive algorithm I implemented).
And advice will be greatly appreciated!

Generate unique lists from other
I have the following code that generates unique lists from other lists:
import itertools def print_results_ordered_in_list(inputx): io = 0 input_list = list(inputx) while io < (len(input_list)): input_list[io] = list(input_list[io]) input_list[io] = sorted(input_list[io], key=int) print(input_list[io]) io += 1 list1 = ['01', '02', '03'] list2 = ['02', '03', '04'] list3 = ['04', '05', '03'] list4 = ['05', '07', '06'] list5 = ['08', '06', '07'] listas = [list1, list2, list3, list4, list5] all_results = set(tuple(set(i)) for i in itertools.product(*listas) if len(set(i)) == 5) print_results_ordered_in_list(all_results)
This generates 42 different lists, among them:
['01', '03', '05', '06', '07'] ['02', '03', '04', '05', '06'] ['01', '03', '04', '05', '07'] ['01', '03', '04', '05', '07'] ['02', '03', '04', '05', '06'] ['03', '04', '05', '06', '08'] ['02', '03', '04', '06', '08'] ['01', '02', '04', '07', '08'] ['01', '04', '05', '06', '08'] ...others lists below...
It prints on the screen all generated lists. But most of the time, the difference from one generated list to another is only in 1 element (in this case, number), example:
['01', '02', '03', '05', '06'] ['01', '02', '03', '05', '07'] ['01', '02', '03', '05', '08']
That is, only the last element has changed.
How do I make the difference be at least 2 elements in all generated lists? We know that for one result to be different from another it is necessary that only 1 element change and this my code already does, but how to make it to be 2? Example:
['01', '02', '03', '05', '06'] ['01', '02', '03', '07', '08'] ['02', '03', '04', '05', '07']
We can see that in addition to being single lists, there are at least 2 distinct elements from one list to another. That's what I want to do.

PHP arrays  unique combinations out of 3 arrays
I'm not even sure how to approach the problem so I'm just stating the problem. Any help is highly appreciated.
There's this array ($colors) of all possible values:
$colors = array ('red','blue','green','yellow');
Then there's an array ($boxes) of all the possible values  consisting of equal number of values as $colors:
$boxes = array ('circular','squared','hexagonal','triangular');
There's this third array which defines the constraints in making the unique combination:
$possible_combos = array ( array('circular','red','blue'), array('squared','red','green'), array('hexagonal','blue','yellow'), array('triangular','red','green') );
Question: How do I get a new array $result with key=>value combinations just that each box is assigned a unique color out of it's possible sets of colors
So a valid $result array would be:
Array ( [circular] => red [squared] => blue [hexagonal]=> yellow [triangular] => green )
NOTE: If you traverse sequentially, 'red', 'blue', 'green' might get assigned to first three 'boxes' and there might not be anything to pick for the fourth box (since 'yellow' is not allowed to be assigned to it.
I'm thinking, to process the least occurring 'colors' first but really unsure how to handle it syntactically.Once again thanks for looking into it, in advance! Even some help with how to approach the problem would be nice.
Following code is not producing the correct output either:
foreach ($colors as $c => $color) { foreach ($boxes as $b => $box) { for ($i=0; $i < count($colors) ; $i++) { if(in_array($possible_combos[$i][1],$colors) && !in_array($possible_combos[$i][1], $result)) { $result[$box] = $possible_combos[$i][1]; unset($colors[$c]); break; } else if(in_array($possible_combos[$i][2],$colors) && !in_array($possible_combos[$i][2], $result)) { $result[$box] = $possible_combos[$i][2]; unset($colors[$c]); break; } } } }

Get Nth combination of a set of elements with loose conditions
Given:
 A list of symbols of size M
 The desired size of combination L
 Symbols may occur any number of times in a combination
 All permutations of any combination of the symbols must be taken into the account
Example: for a list of symbols
(a, b, c)
, and L=4, all of the combinations(a, a, a, a)
,(a, b, a, c)
,(a, c, b, b)
and so on are valid. For the lack of a better term, I called this "loose combinations".The particular ordering of the combinations is not important. Being given the combination index N, the algorithm should return a unique combination from the set of possible combinations that satisfy the conditions. My guess is that the most natural order would be if we consider the combinations as numbers of radix M and length L, so that the normal number order would apply, but that is not strictly necessary to follow.
What is the algorithm to find the Nth combination?
I'm not sure how to find the answer myself, and have been searching if there was an answer for this particular set of conditions elsewhere, but did not find it. All the questions that I find are not interested in combinations with repeating elements like
(a, a, b, b)
and combinations with rearranged order, like(a, a, b, c)
and(a, b, c, a)
or(a, c, a, b)
are treated as the same combination. 
Permutation using probability versus direct frequencies in R?
I'm trying to understand if there is any difference to the following approaches in permutating values based on their frequencies.
Here is an example of the raw data, which gets binned by
hist
:# generate original data set.seed(1) n < 100 x < 20 * rlnorm(n, mean=0, sd=0.2) h < hist(x)
Now, I am sampling from these binned mid values given their frequencies. The first approach extends a vector first, and then samples with replacement. The second approach used the frequency information in the
prob
argument:# approach 1  extend value vector by frequencies and then sample with replacement xs < rep(h$mids, h$counts) x1 < sample(xs, replace = TRUE) # approach 2  sample values based on weighted probability with replacement x2 < sample(h$mids, size = sum(h$counts), prob = h$counts, replace = TRUE)
When I test both approaches in replication, the output looks similar, as I would expect it should be (here I look at the mean and sd of the replicate means):
fun1 < function(x){ xs < rep(h$mids, h$counts) s < sample(xs, replace = TRUE) mean(s) } fun2 < function(x){ s < sample(h$mids, size = sum(h$counts), prob = h$counts, replace = TRUE) mean(s) } set.seed(1) F1 < unlist(lapply(vector("list", 1000), FUN = fun1)) F2 < unlist(lapply(vector("list", 1000), FUN = fun2)) mean(F1); mean(F2) # [1] 20.65432 # [1] 20.63858 sd(F1); sd(F2) # [1] 0.3861233 # [1] 0.3750731
So, are these approaches equivalent? I would think that using probabilities is more computationally efficient since one need not first build the vector of values first.

Permutations interleaved with special values
I am having a real brain block trying to figure this out. I am trying to write a function that will return all the permutations of a list, interleaved with some number of special values.
The function signature:
def interleaved_permutations(values, num_special_values)
An example:
>>> interleaved_permutations([1,2,3,4], 2) [1,x,x,2,3,4] [1,x,2,x,3,4] [1,x,2,3,x,4] [1,2,x,x,3,4] ...
An extra requirement is that the special values can not be first or last in the list.
I know that there must be a way with some crazy itertools foo, but I have not been able to come up with anything remotely close. the closest I have gotten is just getting the permutations of the input values with
itertools.permutations
I am hoping somebody more pythonic than me will be able to help!