w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » ALGORITHM » Page 1
Algebraic form to code
Let T be int. Then V is any int or a nul. Now, expressions can be cons(x y) where x,y are either ints or nuls or other expressions, for example: 1 cons(2 3) cons(cons(4 5) cons(6 7)) L^n is a special kind of expression where the first argument of cons is limited to be T and the innermost atom must be nul. So this cons(1 cons(2 cons(3 nul))) is a valid L^n (specifically L^3), while this is no

Categories : Algorithm

Fast geospatial search geofencing irregular polygons
It sounds like your set of polygons is static. If so, one of the fastest ways is likely to be binary space partitioning. Very briefly, building a BSP tree means picking a single edge from among your billions of polygons, splitting any polygons that cross this (infinite) line into two halves, partitioning the polygons into those on each side of the line, and recursively building a BSP tree on eac

Categories : Algorithm

What is the difference between triangle inequality and path relaxation in Dijkstra's algorithm?
Path relaxation is the process by which we arrive at the shortest paths from source to all vertices. Relaxation of an edge in Dijkstra's algorithm Triangle inequality refers to the lengths of the shortest paths between the vertices. For example the shortest distance between A and B D(A,B) is not greater than D(A,C) + D(C,B) for any other vertex C not lying in the shortest path from A to B.

Categories : Algorithm

How is a query in this example turned into a unit vector using term frequency and normalization?
It's a standard vector normalization. A vector is said to be normalized if its distance from the 0 [(0,0,0) in your case] is exactly 1, which as you can see is the case in this vector (up to rounding difference). Normalization is done by: Let the vector be x = (x_1,x_2,...,x_n) let s = x_1^2 + x_2^2 + ... + x_n^2 [sum of squares] let the normalized vector n = x/sqrt(s) = (x_1/sqrt(s), x_2/sqrt(

Categories : Algorithm

Give an efficient greedy algorithm that finds an optimal vertex cover for a tree in linear time
To select a vertex with highest degree can't guarantee to give the best solution. For example, you have a tree with 7 vertices, edges are listed as follows: 1 2 // (1,2) is connected. 1 3 1 4 2 5 3 6 4 7 The minimum vertex cover is {2,3,4}, however, based on you greedy approach, you will choose {1} first, then you will choose at least 3 vertices to covered the left 3 edges. Indeed, there is a

Categories : Algorithm

Longest common subsequence (LCS) brute force algorithm
It's pretty much the same as DP minus the memoization part. LCS(s1, s2, i, j): if(i == -1 || j == -1) return 0 if(s1[i] == s2[j]) return 1 + LCS(s1, s2, i-1, j-1) return max(LCS(s1, s2, i-1, j), LCS(s1, s2, i, j-1)) The idea is if we have two strings s1 and s2 where s1 ends at i and s2 ends at j, then the LCS is: if either string is empty, then the longest common s

Categories : Algorithm

Definition of Big O with respect to knapsack
That is correct. An algorithm taking as input an integer N that prints all the integers from 0 to N would run in time exponential in the number of bits of N. So when we say an algorithm is "polynomial" or "exponential", what we means depends on what unit we are using. Typically, the unit corresponds to the size of the input (which explains why we measure in terms of the number of bits in the knap

Categories : Algorithm

How would you use sorting to find whether there is a gap between the union of some integer ranges?
That's basically the idea, but you have to deal with overlapping ranges. The easiest way to do that is to just ignore the connection between starting points and ending points, and look only at the count of ranges at a given point: For example, here are some ranges: ---------- ------------------- --- ------- -------

Categories : Algorithm

Partial selection sort vs Mergesort to find "k largest in array"
Here's a general discussion of this particular interview question found from googling: http://www.geeksforgeeks.org/k-largestor-smallest-elements-in-an-array/ As for your question about interviews in general, it probably greatly depends on the interviewer. They usually like to see how you think about things. So, as long as you can come up with some sort of initial solution, your interviewer woul

Categories : Algorithm

Maximum weighted path between two vertices in a directed acyclic Graph
Let f(u) be the maximum profit you can get going from c to u in your DAG. Then you want to compute f(z). This can be easily computed in linear time using dynamic programming/topological sorting. Initialize f(u) = -infinity for every u other than c, and f(c) = 0. Then, proceed computing the values of f in some topological order of your DAG. Thus, as the order is topological, for every incoming edg

Categories : Algorithm

How to prove correctness of the following code?
I'm going to assume your list is sorted, because otherwise it doesn't work. Here is a description of your algorithm that should make it clear why your program works. Suppose your numbers are x[0], x[1], ... , x[n]. The goal is to find two numbers x[i] and x[j] such that their sum is as close to -c as possible. Let's plot the values x[i] + x[j] + c in a (n + 1) by (n + 1) grid, labeling the positiv

Categories : Algorithm

You have a set of N ranges, is it possible to find whether the intersection is empty in O(n)?
Try and see if the maximum of the lower limits is larger than the minimum of the upper limits. If the first is greater than the second, the intersection has to be empty. (If this is not obvious, I'll try to find or construct a proof.) If not, check if the resulting interval [max, min] contains elements of your choice (you didn't mention if you are looking for an interval in the integers, or real n

Categories : Algorithm

looking for an algorithm for Under Water Town
As I understood the filling will go like this: Here is algorithm in pseudo-code and descriptions: 1) Let int h[] be array with houses height. Index is number of house. So length of array is x-range that we take into account (or number of houses). If there is no house at some position there will be 0 (or house with zero height) Let float w[] be array with absolute water height that corresponds w

Categories : Algorithm

Algorithm for maximizing happiness when distributing objects to 2 groups
This can be solved in quadratic time in n using dynamic programming. Let f(i, j) be the maximum possible happiness if last fruit eaten by X is i and last fruit eaten by Y is j. Let me call the first fruit the fruit number 0 and the last one the number n - 1 (0-indexed). Then, you need to calculate f(-1, -1) (initially they have not eaten any fruit). This dynamic programming can be easily calculat

Categories : Algorithm

! Missing number, treated as zero error in latex when using for loop
Don't load algorithm2e when you're using algpseudocode. The former creates an algorithm floating environment, but in order to use algorithmic from algpseudocode, you should load algorithm instead (from the algorithms bundle). documentclass{article} usepackage{algorithm} usepackage[noend]{algpseudocode} egin{document} egin{algorithm} caption{AlgorithmCH election algorithm} label{algorithm

Categories : Algorithm

Algorithm to distribute a discrete number by given percentages while maintaining a minimum of 1
I would assign them randomly until the remaining number of days equals the number of empty groups. emptyGroups = Sum(g); // Random assignment while (n > emptyGroups) { i = chooseAGroup(); if (g_i == 0) emptyGroups--; g_i++; } // Assign the remaining days to empty groups foreach(group) { if n > 0 && g_i == 0) { g_i = 1; n--; } }

Categories : Algorithm

How to get the minimal absolute value of the differences?
If I correctly understand your algorithm/question there is no need to make any calculations during performing a[i]-x, a[j]+x operations. So my suggestion is: 1) make required number of a[i]-x, a[j]+x operations 2) do the following procedure (in pseudo-code): _aSorted[] = sort(_a[]) _dif = max integer value for (i=0; i < _a[].length - 1; i++){ if(abs(_aSorted[i]-_aSorted[i+1]

Categories : Algorithm

Finding a set of nodes which are one-hop neighbors of each other in an adjacency matrix
A set of nodes in a graph that are neighbours of each other is called a clique, and finding the largest clique in a graph, or indeed whether any clique of a specified size even exists in the graph, is a classic NP-hard problem. Some NP-hard problems, called fixed-parameter tractable (FPT) problems, can be solved efficiently even for large n, provided that some problem parameter (besides the size)

Categories : Algorithm

Insert algorithm in Lyx 2.1.1 with line numbers
The default algorithm insertion is just a floating environment. If you want a built-in numbered algorithm, you have to consider adding the algorithm2e module: Then, also add LinesNumbered to your Document > Settings... > LaTeX Preamble. The above assumes a non-ERT approach to numbered-line algorithms. Of course, if you wish, you can go all out with LaTeX ERT to obtain line numbers in algorit

Categories : Algorithm

Algorithm that schedule the right number of tasks to maximize reward: tough or basic?
I suggest to use the Dynamic Programming technique to tackle this problem as it is more straight-forward and intuitive. The setup of the DP is as follow: Let P[i] denotes the optimal reward from week 1 till week i, then we have the following recurrence relation: P[i] = max{ P[i-2] + ti, P[i-1] + bi } for i ≥ 2. And the base cases are P[0] = 0, P[1] = b1 (assume you can only do basic task in w

Categories : Algorithm

Divide Hamiltonian Cycle Optimally
You can solve this problem using dynamic programming in O(m^2) time (maybe you even faster? I didn't try to improve on it). The idea is that for each i and j with i < j, you compute the optimal way W[i][j] to construct one path to v[i] and another disjoint path to v[j], where the two paths use up all of the vertices from v[1] to v[j]. These can be computed efficiently just by looking at the pos

Categories : Algorithm

Need review of my solution. Calculating avarage days of open tickets
There is a bug in your pseudocode, where it says weekarray[k].opendays += convertToDays(weekarray[k] - weekarray[startdate]) This can't be right because, if I understand you code correctly, the convertToDays(...) expression calculates the number of days from startdate to the week 'k'. However, you should be adding at most 7 to opendays for the week 'k' at this point in the loop (compare this w

Categories : Algorithm

Calculate shortest path from start to end visiting certain node
I'm going to suggest a modification of Winata's algorithm inspired by it - it's not great except in easy cases, but I'm beginning to suspect that this is a hard problem. Winata suggested that we compute the shortest paths from p1 and pn to pk, and merge these to get a path from p1 to pn via pk. If this returns an answer that satisfies the extra constraint that no node is visited more than once, t

Categories : Algorithm

Queue-based Bellman-Ford algorithm
Your code for the acyclic one seems correct but depends on what do you mean by one iteration to calculate the shortest path.. If the graph is acyclic (i.e., a DAG) then topological sort will allow us to visit each vertex v once (after examining all of its predecessors) and update dist[v] to its minimum distance. This is done in linear time O(V+E). So your DAG algorithm should look somehow similar

Categories : Algorithm

Johnson's algorithm: what if we modified it?
Notations are not so clear to me. Why do we need to add a vertex and connect it to all other vertices ? Because Johnson's algorithm do the reweighting by running the Bellman-Ford algorithm which in turn requires a single source shortest path problem. Why do we need reweighting? To end up with a non-negative instance which can be solved by running Dijkstra's algorithm. The only requirem

Categories : Algorithm

Binary Search for square root from leetcode oj
The return type int simply means you are return a result which is of type int. It has nothing to do with the algorithm inside the method body. Below I have tried to answer your questions: While(end-start > 1) is used to make sure end is always greater than start. if end-start is 1 or less than 1, that means you have reached end of binary search. You can go ahead and change while(end-start >

Categories : Algorithm

Tortoise and hare algorithm
The tortoise and hare algorithm runs two pointers, one at offset i and the other at offset 2i, both one-based, so initially 1 and 2, and is meant to detect cycles in linked-list-style data structures. And, just to be clear, it compares the pointers rather than data values they point to, I'm unsure whether you understand that so, on the off-chance you didn't, I just thought I'd mention it. The in

Categories : Algorithm

Number Pyramid Algorithm
Here's one solution .... but you should not be lazy, this isn't so hard :) It is written in Java .... What you see in the System.out.print() is "Ternary operator". You need to check if it is two digit number, to reduce the number of empty spaces. public static void Pyramid(int rows) { int r = 1; // r is current row int emptySpaces = rows; while(r <= rows) { //print the em

Categories : Algorithm

Magic code for level binary tree traversal - what is going on?
How do you combine two layer lists of two subtrees and get a layer list of a bugger tree? Suppose you have this tree a / x y where x and y are arbitrary trees, and they have their layer lists as [[x00,x01,...],[x10,x11,...],...] and [[y00,y01,...],[y10,y11,...],...] respectively. The layer list of the new tree will be [[a],[x00,x01,...]++[y00,y01,...],[x10,x11,...]++[y10,y11,...],...

Categories : Algorithm

Singular value decomposition of complex 2x2 matrix
Here's some python code that does the trick. It basically just extracts the complex parts then delegates to the solution from this answer for real 2x2 matrices. I've written the code in python, using numpy. This is a bit ironic, because if you have numpy you should just use np.linalg.svd. Clearly this is intended as example code suitable for learning or translating into other languages in a pinch

Categories : Algorithm

Given binary tree represented as an array, find the pre-order traversal of it
In a binary tree represented as an array, a, typically the root is at a[1]. Given a node at position x, its left child is at a[x*2] and its right child is at a[(x*2)+1]. So the root's left child is at a[2] and its right child is at a[3]. The left child of the node at a[2] is at a[4], and the right child of the node at a[3] is at a[7]. For a node at position x, its parent is at a[x/2]. Given tha

Categories : Algorithm

Neural network with batch training algorithm, when to apply momentum and weight decay
Just some quick comment to this. Stochastic gradient descendent leads most of the times to a non-smooth optimization, and requires a sequential optimization that does not suit current technology advances such as parallel computation. As such, the mini-batch approach try to gain the advantages of the stochastic optimization with the advantages of the batch optimization (parallel computation). Here

Categories : Algorithm

What is the greedy approach for this?
If the numbers are integers you can just xor all the values in your array. The result is the number that is repeated odd number of times(it is correct because x xor x = 0 for any x). The complexity of this algorithm is obviously O(n).

Categories : Algorithm

calculating without using BigInt
You can certainly do this, and I recommend it as an exercise. Beyond that there's little reason to implement this in a language with an existing BigInteger implementation. In case you're looking for an exercise, it's really helpful to do it in a language that supports BigIntegers out of the box. That way you can gradually replace BigInteger operations with your own until there's nothing left to r

Categories : Algorithm

is wikipedia iterative postorder tree traversal pseudo code wrong?
The wikipedia version is wrong for the exact same reason as you've explained it. Here is a probably better pseudo-code, from geeksforgeeks 1.1 Create an empty stack 2.1 Do following while root is not NULL a) Push root's right child and then root to stack. b) Set root as root's left child. 2.2 Pop an item from stack and set it as root. a) If the popped item has a right child and the r

Categories : Algorithm

What algorithm is used to implement HermiteH function (mathematica)
http://www.maplesoft.com/support/help/maple/view.aspx?path=HermiteH For n different from a non-negative integer, the analytic extension of the Hermite polynomial is given by where KummerM is a Kummer's function (of the first kind) M and Γ is a gamma function

Categories : Algorithm

how to prove this is a matroid in greedy solving?
1.P is finite as stated in qusetion 2.q has inheritance because when we choose B all of its subset still has at most one member of pi 3.q has substitution property as when we have |A| < |B| then B has some memebers of Pi that are not in A so we can add them to A and still it has at most one member of Pi

Categories : Algorithm

Write an algorithm to return an array such that every number k from 1..n is occurring exactly twice and is k distance apart from its replica
This is an exact cover problem, which you can solve with Algorithm X. (And it's a nicer, simpler example than Sudoku.) You have the following constraints: each number must be used exaclty twice and each slot in the array can only be occupied by one number For your problem with n = 3, you get the following matrix: [0] [1] [2] [3] [4] [5] 1 2 3 --- --- --- --- --- --- --- --- ---

Categories : Algorithm

Mergesort recurrence formulas - reconciling reality with textbooks
Question 1: Where are you getting your facts? To obtain theta(nlogn) complexity you need T(n) = a T(n/b) + f(n), where a > 1, b > 1 and f(n) = cn + d. c != 0 Note: There are additional constraints, dictated by the Master theorem You cannot derive from reccurence relation based on T(n) > T(n/2) + 3n + 3. You probably forgot that the cost of an array of size n is the cost of the merge

Categories : Algorithm




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