001 // GraphLab Project: http://graphlab.sharif.edu 002 // Copyright (C) 2008 Mathematical Science Department of Sharif University of Technology 003 // Distributed under the terms of the GNU General Public License (GPL): http://www.gnu.org/licenses/ 004 package graphlab.plugins.main.saveload.matrix; 005 006 import graphlab.graph.graph.EdgeModel; 007 import graphlab.graph.graph.GraphModel; 008 import graphlab.graph.graph.GraphPoint; 009 import graphlab.graph.graph.VertexModel; 010 import graphlab.library.BaseEdge; 011 import graphlab.library.BaseGraph; 012 import graphlab.library.BaseVertex; 013 014 import javax.swing.*; 015 import java.util.HashMap; 016 import java.util.Scanner; 017 018 /** 019 * @author Azin Azadi 020 */ 021 public class Matrix { 022 023 public static <vt extends BaseVertex, et extends BaseEdge<vt>> 024 boolean[][] graph2Matrix(BaseGraph<vt, et> g) { 025 int n = g.getVerticesCount(); 026 boolean[][] ret = new boolean[n][n]; 027 HashMap<Integer, vt> m = new HashMap<Integer, vt>(); 028 int i = 0; 029 for (vt _ : g) { 030 m.put(i++, _); 031 } 032 for (i = 0; i < n; i++) 033 for (int j = 0; j < n; j++) { 034 ret[i][j] = g.isEdge(m.get(i), m.get(j)); 035 } 036 return ret; 037 } 038 039 public static void Matrix2Graph(boolean[][] mat, GraphModel g) { 040 int n = mat.length; 041 int nn = mat[1].length; 042 if (n != nn) { 043 JOptionPane.showMessageDialog(null, "not a valid matrix graph"); 044 return; 045 } 046 VertexModel[] vertices = new VertexModel[n]; 047 for (int i = 0; i < n; i++) { 048 VertexModel v = new VertexModel(); 049 g.insertVertex(v); 050 v.setLocation(new GraphPoint(Math.random() * 500, Math.random() * 500)); 051 vertices[i] = v; 052 } 053 for (int i = 0; i < n; i++) { 054 for (int j = 0; j < n; j++) { 055 if (mat[i][j]) 056 g.insertEdge(new EdgeModel(vertices[i], vertices[j])); 057 } 058 } 059 } 060 061 public static String Matrix2String(boolean[][] mat) { 062 int a = mat.length; 063 if (a == 0) 064 return ""; 065 int b = mat[0].length; 066 String ret = ""; 067 for (int i = 0; i < a; i++) { 068 for (int j = 0; j < b; j++) { 069 ret += (mat[i][j] ? "1" : "0"); 070 ret += " "; 071 } 072 ret += "\n"; 073 } 074 return ret; 075 } 076 077 public static boolean[][] String2Matrix(String s) { 078 int n = 0; 079 for (int i = 0; s.charAt(i) != '\n'; i++) { 080 char c = s.charAt(i); 081 if (c == '1' || c == '0') 082 n++; 083 } 084 System.out.println(n); 085 boolean ret[][] = new boolean[n][n]; 086 Scanner sc = new Scanner(s); 087 int i = 0; 088 while (sc.hasNextLine()) { 089 for (int j = 0; j < n; j++) { 090 ret[i][j] = sc.nextInt() == 1; 091 } 092 i++; 093 // ## \/ ? 094 sc.nextLine(); 095 } 096 return ret; 097 } 098 }