Algorithm to generate interval graph - math

I wonder if there is any algorithm or some easy procedure to generate an interval graph?
I need to generate interval graphs with n nodes, where n is changing for 1 to, say, 10000.
If it is possible, I need an incidence matrix representation of the graph.
An additional restriction is not to have all these graphs complete.
Thanks everyone in advance!
==ADDITION==
Here is an implementation in Java:
public Object generate(int numberOfNodes) {
int listCapacity = numberOfNodes * 2;
List<Integer> arr = new ArrayList<Integer>();
int[][] adjacencyMatrix = new int[numberOfNodes][numberOfNodes];
Integer nodeNumber = 0;
for (int i = 0; i < listCapacity; i = i + 2) {
arr.add(nodeNumber);
arr.add(nodeNumber);
nodeNumber++;
}
Collections.shuffle(arr);
for (int i = 0; i < numberOfNodes; i++) {
for (int j = arr.indexOf(i); j < arr.lastIndexOf(i); j++) {
adjacencyMatrix[i][arr.get(j)] = 1;
adjacencyMatrix[arr.get(j)][i] = 1;
}
adjacencyMatrix[i][i] = 0;
}
return new Graph(adjacencyMatrix);
}
Though, in some cases it fails to produce interval graph.

One possible way to generate an interval graph with N nodes:
create an array [1, 1, 2, 2, ... n, n]
shuffle the array
create a graph:
each node v_i corresponds to the pair of occurences of i in the shuffled array
two nodes v_i and v_j are connected with an edge iff i and j are interleaved in the array. That is i j i j or i j j i, but not i i j j. In other words, the intervals i and j intersect.
This graph is guaranteed to be an interval graph (every node is an interval in the original array), and every graph is possible to create this way.

Related

Find the number of possible sums which add to N using (1,...,K)

I have the following problem to solve: given a number N and 1<=k<=N, count the number of possible sums of (1,...,k) which add to N. There may be equal factors (e.g. if N=3 and k=2, (1,1,1) is a valid sum), but permutations must not be counted (e.g., if N=3 and k=2, count (1,2) and (2,1) as a single solution). I have implemented the recursive Python code below but I'd like to find a better solution (maybe with dynamic programming? ). It seems similar to the triple step problem, but with the extra constraint of not counting permutations.
def find_num_sums_aux(n, min_k, max_k):
# base case
if n == 0:
return 1
count = 0
# due to lower bound min_k, we evaluate only ordered solutions and prevent permutations
for i in range(min_k, max_k+1):
if n-i>=0:
count += find_num_sums_aux(n-i, i, max_k)
return count
def find_num_sums(n, k):
count = find_num_sums_aux(n,1,k)
return count
This is a standard problem in dynamic programming (subset sum problem).
Lets define the function f(i,j) which gives the number of ways you can get the sum j using a subset of the numbers (1...i), then the result to your problem will be f(k,n).
for each number x of the range (1...i), x might be a part of the sum j or might not, so we need to count these two possibilities.
Note: f(i,0) = 1 for any i, which means that you can get the sum = 0 in one way and this way is by not taking any number from the range (1...i).
Here is the code written in C++:
int n = 10;
int k = 7;
int f[8][11];
//initializing the array with zeroes
for (int i = 0; i <= k; i++)
for (int j = 0; j <= n; j++)
f[i][j] = 0;
f[0][0] = 1;
for (int i = 1; i <= k; i++) {
for (int j = 0; j <= n; j++) {
if (j == 0)
f[i][j] = 1;
else {
f[i][j] = f[i - 1][j];//without adding i to the sum j
if (j - i >= 0)
f[i][j] = f[i][j] + f[i - 1][j - i];//adding i to the sum j
}
}
}
cout << f[k][n] << endl;//print f(k,n)
Update
To handle the case where we can repeat the elements like (1,1,1) will give you the sum 3, you just need to allow picking the same element multiple times by changing the following line of code:
f[i][j] = f[i][j] + f[i - 1][j - i];//adding i to the sum
To this:
f[i][j] = f[i][j] + f[i][j - i];

How to calculate mean value in a dictionary?

I'm trying to compute the mean value of a dictionary which have lot of lists
My dictionary looks like:
{0:[0,1,3,6,1,-5,....],1:[0,3,7,3,-5,2,...],...}
with a total of k entries and lists of lenght N.
However, I am NOT trying to compute the mean value of each list, what I need is to compute the mean value bewteen elements of the lists such (a,b)=mean, i.e. looking at the dictionary above (0,0)=0, (1,3)=2, (3,7)=5,....
Is there a way to compute something like this?
Thanks.
You can unwrap the values and use zip to correlate matching indexes:
from numpy import mean
result = [mean(x) for x in zip(*(d.values()))]
Given that all lists are of the same length:
var k = Object.keys(json).length; // k, number of lists
var n = json[0].length; // N, elements in lists
for (var i = 0; i < n; i++) {
var sum = 0;
for (var j = 0; j < k; j++) {
sum += json[j][i];
}
var mean = sum / k;
console.log(mean);
}

Solving linear equations with numeric.js

I must be missing something really simple here. I've got some JS code that creates simple linear systems (I'm trying to create the shortest line between two skew lines). I've gotten to the point where I have Ax = b, and need to solve for x. A is a 3 x 2 matrix, b is 3 x 1.
I have:
function build_equation_system(v1, v2, b) {
var a = [ [v1.x, v2.x], [v1.y, v2.y], [v1.z, v2.z] ];
var b = [ [b.x], [b.y], [b.z]];
return numeric.solve(a,b)
}
Numeric returns a 1 x 3 matrix of NaNs, even when there is a solution.
Using numeric you can do the following:
Create a function which computes the pseudoinverse of your A matrix:
function pinv(A) {
return numeric.dot(numeric.inv(numeric.dot(numeric.transpose(A),A)),numeric.transpose(A));
}
Use that function to solve your linear least squares equation to get the coefficients.
var p = numeric.dot(pinv(a),b);
I tried your initial method of using numeric.solve and could not get it to work either so I'd be interested to know what the problem is.
A simple test...
var x = new Array(10);
var y = new Array(10);
for (var i = 0; i < 10; ++i) {
x[i] = i;
y[i] = i;
}
// Solve for the first order equation representing this data
var n = 1;
// Construct Vandermonde matrix.
var A = numeric.rep([x.length, n + 1], 1);
for (var i = 0; i < x.length; ++i) {
for (var j = n-1; j >= 0; --j) {
A[i][j] = x[i] * A[i][j+1];
}
}
// Solves the system Ap = y
var p = numeric.dot(pinv(A),y);
p = [1, 2.55351295663786e-15]
I've used this method to recreate MATLAB's polyfit for Javascript use.

JGraphX Takes a Long Time to Construct Graph

I'm constructing a graph with JGraphX. Using the following code, it takes an inordinately long time to build compared to similar graph implementations like JGraphT. Why would this be? The vertices are created quickly, but the nested loops that create the edges take a long time, especially when the array sizes are 1000.
Vertex[] verts = new Vertex[1000]; // My own vertex class
mxCell[] cells = new mxCell[1000]; // From com.mxGraph.model.mxCell
// Create graph
mxGraph mx = new mxGraph(); // from com.mxgraph.view.mxGraph
// Create vertices
for(int i = 0; i < verts.length; i++)
{
verts[i] = new Vertex(Integer.toString(i));
cells[i] = new mxCell(verts[i]);
mx.getModel().beginUpdate();
mx.insertVertex(null, Integer.toString(i), cells[i], 1, 1, 1, 1);
mx.getModel().endUpdate();
}
System.out.println("Vertices created.");
// Connect graph
Random r = new Random();
for(int j = 0; j < verts.length; j++)
{
for(int k = 0; k < verts.length; k++)
{
if(k != j)
{
if(r.nextInt(5) == 0) // Random connections, fairly dense
{
mx.getModel().beginUpdate();
mx.insertEdge(null, Integer.toString(k) + " " + Integer.toString(j), "", cells[j], cells[k]);
mx.getModel().endUpdate();
}
}
}
}
System.out.println("Finished graph.");
begin and end updates are meant for combining operations into one. Ending an update causes a complete validation of the graph. Here you're wrapping each atomic operation only, they have no effect.
Remove the begin/ends you have an put a begin after you create the graph and the end at the bottom of this code section and try that.

number of k-ary tree from pre-order and post-order traversals

Suppose pre-order and post-order traversals and k are given. How many k-ary trees are there with these traversals?
An k-ary tree is a rooted tree for which each vertex has at most k children.
It depends on the particular traversal pair. For instance
pre-order: a b c
post-order: b c a
describes only one possible tree (the fewest possible, unless you include inconsistent traversal pairs). On the other hand:
pre-order: a b c
post-order: c b a
describes 2^(3-1) = 4 trees (the most possible amongst all scenarios where the traversals have 3 nodes and k can be anything), namely the 4 3-node lines.
If you want to know the number of possible binary trees having Pre-order and Post-order traversals, you should first draw one possible tree. then count the number of nodes with only one child. The total number of possible trees would be : 2^(Number of single-child nodes)
as an example:
pre: adbefgchij
post: dgfebijhca
i draw one tree that has 3 single-child nodes. So , the number of possible trees is 8.
First determine the corresponding range of sub-tree by DFS, and get the amount of sub-tree, then solve it through combination of the sub-trees.
const int maxn = 30;
int C[maxn][maxn];
char pre[maxn],post[maxn];
int n,m;
void prepare()
{
memset(C,0,sizeof(C));
for(int i=0;i<maxn;i++)
{
C[i][0] = 1;
}
for(int i=1;i<maxn;i++)
{
for(int j=1;j<=i;j++)
{
C[i][j] = C[i-1][j-1] + C[i-1][j];
}
}
return;
}
int dfs(int rs,int rt,int os,int ot)
{
if(rs == rt) return 1;
int son = 0,res = 1;
int l = rs + 1,r = os;
while(l <= rt)
{
while(r < ot)
{
if(pre[l] == post[r])
{
son++;
break;
}
r++;
}
res *= dfs(l , l + r - os , os , r);
l += r - os + 1;
rs = l - 1;
os = ++r;
}
return res * C[m][son];
}
int main()
{
prepare();
while(scanf("%d",&m) && m)
{
scanf("%s %s",pre,post);
n = strlen(pre);
printf("%d\n",dfs(0,n-1,0,n-1));
}
return 0;
}

Resources