w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Find maximum number of valid combinations for elements of two arrays
Assuming: Function is_coprime_pair(pair) is defined, accepts a list of length 2 and returns True for a pair of prime numbers a and b are iterables to combine import itertools not_coprimes = itertools.filterfalse(is_coprime_pair, itertools.product(a, b)) not_coprimes will hold all pairs that don't contain two prime numbers

Categories : Python

Finding common elements in two arrays of different size
Assuming you can have "holes" in your matched sequence (A = [1,3,2] AND B = [1,4,2] Then MatchSet = {1,2}) Maybe I am wrong but you could try this pseudo code: i <- 0; j <- 0; jHit <- -1 matchSet <- Empty While i < Length(A) AND j < Length(B): If A[i] == B[j] Then matchSet.add(A[i]) i <- i+1 jHit <- j End If j <- j+1 If j == Length(B) Then i <- i+1 j <- jHit+1 End If End Loop The first index (i) points to the next element of A not found in B whereas (j) is used to look for the next element of B (after the last element found in A). This yould give you a time complexity of O(mN) and space usage of O(N). Here you have an implementation in Python: def match(A,B): i = 0 j = 0 jHit = -

Categories : Arrays

Finding number of largest sum sub-arrays in an array using Kadane's algorithm
Kadane's algorithm keeps track of the maximum value of a sequence ending at the current point, and the maximum value seen so far. Here is a Python implementation based on the wikipedia page: def kadane(A): max_ending_here = max_so_far = 0 for x in A: max_ending_here = max([x,0,max_ending_here+x]) max_so_far = max(max_so_far,max_ending_here) return max_so_far We can modify the algorithm to keep track of the count of such sequences by adding two variables: count_with_max_ending_here to count the number of sequences ending at the current point with values that sum to max_ending_here count_with_max to count the number of sequences found so far with the maximum value Kadane's algorithm can be straightforwardly changed to keep track of these variables while st

Categories : Algorithm

Finding the number of form elements
As Amine hinted, use the :input selector: $(':input').length

Categories : Jquery

Finding the number of elements between i and j in an integer array in o(1)
Dim result() as integer Dim C(1000) as integer Dim Buff() as integer Dim i as integer=50 dim j as integer=450 for count =0 to c.count-1 if c(count)>i and c(count)<j then dim length as integer=buff.count-1 redim result(lenght+1) for buffcount=0 to buff.count result(buffcount)=buff(buffcount) next result(result.count-1)=c(count) redim buff(result.lenght-1) buff=result end if next

Categories : Arrays

Regular expression for finding JavaScript arrays in html document
A pattern like this should work: ^var w+ = new Array(.*);$ This will match the beginning of the string (or line in multi-line mode), followed a literal var, followed by one or more 'word' characters followed by a literal = new Array( followed by zero or more of any characters, followed by a literal ); and the end of the string (or line in multi-line mode).

Categories : C

Arrange arrays elements with javascript and jquery
I think you can use something like this: var ROW_HEIGHT = 100; //assume 100px, but you can change this var rowsCount = 7; var rows = []; for(var i = 0; i < rowsCount; i++) { rows[i] = []; } for(var i = 0; i < arrayOfDivs.length; i++) { var position = arrayOfDivs[i]; //The assumption is that the table starts at position 0. If not, you will //have to subtract the table's top position from topPosition var rowNumber = Math.floor(position.topPosition / ROW_HEIGHT); rows[rowNumber].push(position); } This will end up grouping divs into rows, based on their topPosition. So anything that with 0 <= topPosition < 100 will be in row[0] (first row), anything with 100 <= topPosition < 200 will be in row[1] (second row) and so on. You can then iterate over thes

Categories : Javascript

Combine elements from two multidimensional arrays in JavaScript
Here you have: var total = [[1370923200000, "66"],[1371009600000, "42"],[1371096000000, "23"]]; var successful = [[1370923200000, "5"],[1371096000000, "2"],[1371182400000, "0"]]; var combined = {}; for(var i=0; i<total.length; i++){ combined[total[i][0]] = {date: total[i][0], total: total[i][1]}; } for(var i=0; i<successful.length; i++){ if(successful[i][0] in combined){ combined[successful[i][0]].successful = successful[i][1]; } else{ combined[successful[i][0]] = { date: successful[i][0], successful: successful[i][1] }; } } var result = []; for(var key in combined){ result.push(combined[key]); } alert(result.toSource()); And a working fiddle http://jsfiddle.net/eRjeZ/

Categories : Javascript

Need help finding all possible combinations, method almost complete
int[][] combs = combinationsOf(combinations, 5); for (int i = 0 ; i < combs.length ; i++) { for(int j = 0 ; j < combs[i].length ; j++) { System.out.print(combs[i][j] + ", "); } System.out.println(""); } public static int[][] combinationsOf(int[] colorShape, int numPositions) { int[][] combs = new int[(int)(Math.pow(colorShape.length, numPositions))][numPositions]; int[] holding = new int[numPositions]; for(int i = 0 ; i < numPositions ; i++) { holding[i]=0; } for(int i = 0 ; i < combs.length ; i++) { for(int j = 0 ; j < numPositions ; j++) { combs[i][j] = colorShape[holding[j]]; } incrementHolding(holding, colorShape.length);

Categories : Java

Algorithm for finding all possible key combinations in given range
Assuming that passwords can consist of combinations of 89 possible characters (a-z, A-z, 0-9, space, and all the different symbol keys on a Windows keyboard), a there there are 82 the the 15th power different combinations of 15 characters (82 * 82 * 82 ... ). In other words, a lot. If you want to use just letters, and you differentiate between upper and lower case, there would be 52 ** 15 possible 15-letter combinations. If you want to take in the possibility of shorter strings as well you could write something like (pseudocode): long combos = 0 for i = 6 TO 20 -- legal password lengths combos = combos + POW(52, i) print "there are " + combos.ToString() + " possible passwords between 6 and 20 characters" To actually enumerate and print the permu

Categories : Misc

C++: Finding all combinations of array items divisable to two groups
I can suggest the following solution: The total number of combinations is 2^(number of weights). Using a bit logic we can loop through the all combinations and calculate maxDistance. Bits in the combination value show which weight goes to which vehicle. Note that algorithm complexity is exponential and int has a limited number of bits! float maxDistance = 0.f; for (int combination = 0; combination < (1 << ARRAYSIZE(weights)); ++combination) { int weightForVehicleONE = 0; int weightForVehicleTWO = 0; for (int i = 0; i < ARRAYSIZE(weights); ++i) { if (combination & (1 << i)) // bit is set to 1 and goes to vechicleTWO { weightForVehicleTWO += weights[i]; } else // bit is set to 0 and goes to vechicleONE

Categories : C++

Combinatorics: Need to formulate and list combinations from multiple arrays to display mapping output
I think this works... EDIT: updated Combine() to make it insensitive to the base of the arrays contained in the submitted collection and change Do-Loop for For-Next Sub Tester() Dim arr(1 To 3, 1 To 4) arr(1, 1) = "CodeB|CodeC|CodeD|" arr(1, 2) = "CodeE|" arr(1, 3) = "CodeF|CodeG|" arr(2, 1) = "CodeH|" arr(2, 2) = "CodeI|CodeJ|" arr(2, 3) = "CodeK|CodeL|CodeM|CodeN|" arr(2, 4) = "CodeO|" arr(3, 1) = "CodeQ|" arr(3, 2) = "CodeR|CodeS|" DoCombinations arr End Sub Sub DoCombinations(arr As Variant) Dim r As Long, c As Long Dim nc As Long, nr As Long Dim a Dim col As Collection, col2 As New Collection Dim final() As String, tmp nr = UBound(arr, 1) nc = UBound(arr, 2) For r = 1 To nr 'loop through first dimension Set col = New Collection

Categories : Vba

Get all the combinations of N elements of multidimensional array
Updated Per your restriction that elements that are contained in the same array in the beginning cannot be combined I've modified the algorithm to the following: Here is the updated jsfiddle that now even outputs the data in the correct format :) http://jsfiddle.net/QKg2H/7/ function getCombinations(arr, n) { if(n == 1) { var ret = []; for(var i = 0; i < arr.length; i++) { for(var j = 0; j < arr[i].length; j++) { ret.push([arr[i][j]]); } } return ret; } else { var ret = []; for(var i = 0; i < arr.length; i++) { var elem = arr.shift(); for(var j = 0; j < elem.length; j++) { var childperm = g

Categories : Javascript

R- all pairwise combinations of elements from two lists
Life is made easier if you put your models and data frames into lists. modlst <- list(model.1, model.2, ....) datlst <- list(data.1, data.2, ....) out <- lapply(modlst, function(mod) { lapply(datlst, function(dat) predict(mod, dat)) })

Categories : R

How to get all the unique n-long combinations of a set of duplicatable elements?
Lets say you've got N input elements, and you want a K-long combination. All you need to do is to count in base N, scoped of course, to all numbers that have K digits. So, lets say N = {n0, n1, ... nN} You'd start from the number [n0 n0 ... n0], and count all the way up to [nN nN ... nN] If you'd like help in understanding how to count in another base, you can get that here Each number that you compute maps to one of the K-long combinations that you need. I think an example will help I'll use your values. N = {a, b, c} So we want to count in base 3. Since we want 2-long combinations, we only care about 2-digit numbers. The smallest 2-digit base 3 number is 00, so we start there. By counting in base 3, we get: 00 01 02 10 11 12 20 21 22 Ok, so now to convert these numbers into a

Categories : C#

Generate list of all possible combinations of elements of vector
You're looking for expand.grid. expand.grid(0:1, 0:1, 0:1) Or, for the long case: n <- 14 l <- rep(list(0:1), n) expand.grid(l)

Categories : R

Number of combinations of football pool
Disclaimer: your logic is based on unpredictable assumptions. Please do not relay on it if youre betting real money. It's all more complicated then you think it is. There is only one reliable way of betting and earning (requires a lot of money to get started and proper and good understanding of bookmakers policies) and it's called sure bets. But please, do not get into it. Now, back to your original question. You can have a function return the number of combinations based on the input » combinations multipliers Let's assume that combinations multipliers 1 - 1 2 - 1X 3 - 1X2 1 represents either home or away win, 1 combination 2 stands for home win or draw, away win or draw, 2 combinations 3 is default: win, draw, win The code: Sub Combination_Prediction() ' combination

Categories : Algorithm

Lisp: How to get all possible combinations of the elements from lists contained on a list?
wvxvw removed their answer that pointed to a function from Alexandria, but it does provide a very similarly named function that actually does what you want. Instead of alexandria:map-combinations, you need alexandria:map-product, e.g. (apply #'alexandria:map-product #'list '((1 2) (1 2))) evaluates to ((1 1) (1 2) (2 1) (2 2))

Categories : Algorithm

How to compute the total number of combinations between three datasets?
Using this , you can do the following for example: corpij <- function(i,j,data) { res <- tryCatch(cor.test(data[,i],data[,j])$parameter+2, error = function(e) NA) corp <- Vectorize(corpij, vectorize.args=list("i","j")) result = apply(dat, c(1,2), function(x) outer(1:ncol(x),1:ncol(x), corp,data=x)) outer will perform all the columns combinations.

Categories : R

Find all possible combinations of a String representation of a number
Just us breadth-first search. for instance 121 Start from the first integer, consider 1 integer character first, map 1 to a, leave 21 then 2 integer character map 12 to L leave 1.

Categories : Algorithm

Generate all combinations of an array with a given number of slots in PHP
$option = array("a", "b"); function combinations($option, $number) { $combo = array_fill(0, $number, 0); $num_option = count($option); while (true) { // output the combination $output = array_fill(0, $number, 0); for ($i = 0; $i < $number; ++$i) { $output[$i] = $option[$combo[$i]]; } echo implode(" - ", array_reverse($output)) . "<br>"; // compute next combination $incpos = 0; while ($combo[$incpos] == $num_option-1) { $combo[$incpos++] = 0; if ($incpos >= $number) { // we wrapped around - end return; } } ++$combo[$incpos]; } } combinations($option, 5); This code works by treating the current combin

Categories : PHP

Finding number of ways a piece on a chess board can move with number and type of moves given
The key to this type of problem is to reuse partial results by using a sliding window. For example, suppose you knew the sum of elements 1 to 1000 of an array X was 1234, and wanted to know the sum of elements 2 to 1001. The fast way is to compute 1234+X[1001]-X[1]. In this problem, your constraint on the absolute value means that you are trying to add all the values in a diamond shape. If we now slide the window one step diagonally, we can compute the new sum by adding on the values on the bottom left, and taking away the ones on the top left: ..A.. ..-.. ..... .AAA. .--A. ...B. ..A.. -> ..A++ = ..BBB ..... ...+. ...B. In the diagram we are adding the values marked with +, and taking away the values marked with -. This has reduced the number of operations from O(

Categories : Algorithm

Regular Expression PHP finding the number after a certain number of # characters
You can use explode. $parts = explode('#', $string, 16); $item = substr($parts[15], 0, 1); And in PHP >= 5.4.0, you can write it like this: $string = '09:00 23/02/2012#3.5#2.2#91#3.7#7.4#170#S#1033.1#(+1 Hpa / 3H).#0#3H##4.5#Plus de 2500m #6####00#### Brume.#'; $index = 16; var_dump(explode('#', $string)[$index - 1]);

Categories : PHP

Finding the nearest multiple of a number to another number - Objective C
Try this: -(int)differenceToNextPowerOfTwo:(int)n { unsigned int v = n; v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v - n; } Source: http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2

Categories : Objective C

Finding number of permutations of 'p' numbers that sum to a given number 'n'
Contrary to my comment, this problem is actually easier to solve if we count the number of sets and the permutations of those sets at the same time. If we only need to count instead of actually generating each of the sets, we can do so directly with some simple combinatorics. Let's fix p = 3, n = 5 for our example and imagine that we have n = 5 balls: o o o o o Now the question is equivalent to, how many ways can we split the balls into groups of 3 where each group can have [0, 5] balls? Imagine if we had p - 1 = 2 sticks that we could individually place anywhere: before all five balls, after all five balls, and between any two balls. For example: | o o | o o o => (0, 2, 3) o | | o o o o => (1, 0, 4) o o o o | | o => (4, 0, 1) Notice how the questions are equivalent? Anyway

Categories : Algorithm

Javascript calculate the number of elements under the mouse pointer as the mouse moves
If you don't mind using jQuery -- Use the technique in this question -- jQuery: how do I get the element underneath my cursor? -- to trigger the update whenever the mouse moves over a new element. Then you can use this query method -- .parents() -- to get an array of all of the parents of the element. The number of elements will be the length of the array + 1 (the element itself). If you don't want to count <html> and <body> then you can subtract two.

Categories : Javascript

Anyone knows an algorithm for finding "shapes" in 2d arrays?
I think this question can be reduced to a convex hull problem if we consider each # as point x,y then convex hull be give us the x,y of all the # which are absent http://en.wikipedia.org/wiki/Convex_hull I will try to code it in leisure ..

Categories : Algorithm

Recursively get all possible combinations of a set of numbers in Javascript
You might want to take a look at the following algorithm that generates the next permutation lexicographically. The initial array must be sorted in order ascending before passing to the generation algorithm. The following algorithm generates the next permutation lexicographically after a given permutation. It changes the given permutation in-place. Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation. Find the largest index l such that a[k] < a[l]. Swap the value of a[k] with that of a[l]. Reverse the sequence from a[k + 1] up to and including the final element a[n].

Categories : Javascript

How do I take a JS array that has some elements that are also arrays and make ALL array elements top level elements
You don't need the second step to have an array of arrays, just join then split it by the comma: var array = ["item1", "item2", "item3, item4", "item5", "item6"] console.log(array.join(',').split(',')); Example fiddle

Categories : Javascript

Intersection of arrays in PHP. Finding matching Pairs
if you are looking for adjacent matching, $temp = null; $last_result = array(); foreach($a as $key => $value){ if(is_null($temp)){ $temp = $value; } else{ $result = array_intersect_assoc($temp, $value); if(!empty($result)) array_push($last_result, $result); $temp = $value; } } print_r($last_result); otherwise just use array_intersect_assoc for a example you can do like this $res = array_intersect_assoc($a[0],$a[1],$a[2]); print_r($res);

Categories : PHP

Finding Median in Three Sorted Arrays in O(logn)
This algorithm works for two sorted arrays of same sizes but not three. After the one iteration, you eliminates half of the elements in A and C but leaves B unchanged, so the number of elements in these arrays are no longer the same, and the method no longer apply. For arrays of different sizes, if you apply the same method, you will be removing different number of elements from the lower half and upper half, therefore the median of the remaining elements is not the same as the median of the original arrays. That being said, you can modify the algorithm to eliminate same number of elements at both end in each iteration, this could be in efficient when some of the arrays are very small and some are very large. You can also turn this into a question of finding the k-th element, track the nu

Categories : Arrays

Javascript Regex Pattern Capture - all possible combinations
this works for me var str='||1|| Jam Jam jambura jadu tu sikh jambura'; reg = /(?!||(d+)|||jambura).+?jambura/g; re = /(?![|]+)d+(?=[|]+)/ alert('page '+str.match(re)+': '+str.match(reg).length+' matches'); Try Fiddle the idea is to match ||d+|| first, then only jumbara. Actually, I spent half of a night to find a solution, so I don't remember why I started to use ?! here, but it works

Categories : Javascript

finding data in Matlab for common dates among n arrays
Suppose you have sets A, B, C and want to find elements that occur in all of them, you can nest intersections. It can be done like this: mySet = intersect(intersect(A,B),C) If you are a lazy typist, you can also check out the mintersect File Exchange submission that basically does just this. Then it can be done like this: mySet = mintersect(A,B,C)

Categories : Arrays

extract elements from list of lists with variable number of elements and NAs R
So this can be marked as answered: SimonO101's solution (checking for NA values): lapply(mytestlist, function(x) { if( all(is.na(x)) ){ c(a=0,b=1,c=0) } else { x$nums } }) My solution (checking for named list elements): lapply(mytestlist, function(x) { if('nums' %in% names(x)) { x$nums } else { c(a=0, b=1, c=0) } })

Categories : R

Number of sets for which there exists a unique subset for all number from 1 to n such that sum of elements of subset is equal to the number
Think of a N by N matrix where each element counts up to N. Build this matrix with 2 loops. Then each row that sums to N is a solution. When N = 5 build: 0 0 0 0 0 0 0 0 0 1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4 0 0 0 0 5 SOLUTION 0 0 0 1 1 0 0 0 1 2 0 0 0 1 3 0 0 0 1 4 SOLUTION 0 0 1 0 1 etc.

Categories : Misc

How to add elements from sublists with 2 elements (the first element is a string and the second one a number)?
You just need to break out the string versus the number: sum_fire( [[_,N]|Tail], Sum ) :- sum_fire( Tail, S1 ), Sum is N + S1. sum_fire( [], 0 ). So I'm using [_,N] instead of H for the head item because I want what's inside (the number N). I don't care about the string for the sum, so it's _.

Categories : Prolog

XML Scheme: Complex type using any number of elements any number of times
It is the <xsd:choice> that must be unbounded here. You correct schema should look like this: <xsd:element name="foo"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element ref="p"/> <xsd:element ref="f"/> <xsd:element ref="summary"/> </xsd:choice> <xsd:attribute ref="type"/> </xsd:complexType> </xsd:element> Setting maxOccurs="unbounded" by each element (p, f, summary) won't make any difference here. It just allows you to repeat the same element many times, but not mix with others.

Categories : Xml

mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables
The characters in the string should not be separated by commas: $stmt->bind_param("sss...", /* variables */); You can see this format demonstrated in the examples on the manual page.

Categories : Mysql

Finding multiple elements
In case someone looks for this in the future, I got it to work: findElements(By.className("someclass")).then(function(elements_arr){ console.log(elements_arr.length); }); According to their source code, findElements returns a promise https://code.google.com/p/selenium/source/browse/javascript/webdriver/webdriver.js#803

Categories : Javascript

Finding Elements in Linq to XML
Following code give you the account number of the matching element, members.Where(x=> x.Element("AccountName").Value==validationName).Select(x=> x.Element("AccountNumber").Value).FirstOrDefault();

Categories : C#



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.