Solving Sudoku in SQL?
Hi. I'm wondering if one could solve a Sudoku puzzle with a SQL query given the initial configuration of the Sudoku is stored in a database table. Suppose I have a database table named InitSudoku storing the initial configuration of a 5x5 Sudoku. Each row in the table indicates which number (1 to 25) is initially placed in which square of the puzzle. For example, the row (15,3,9) means the number 15 is initially placed in the square at the 3rd row and the 9th column of the puzzle. What I would like to get is a result set that would give me a completion of the Sudoku. Does anyone think that is doable strictly within SQL with one or more queries (without using a procedural language like C or Java, which would require coding up an algorithm of solving Sudoku)?
Thanks.
The same guru has improved on this solution in 11gr2:
[http://technology.amis.nl/blog/6404/oracle-rdbms-11gr2-solving-a-sudoku-using-recursive-subquery-factoring|http://technology.amis.nl/blog/6404/oracle-rdbms-11gr2-solving-a-sudoku-using-recursive-subquery-factoring]
[http://tonyhasler.wordpress.com]
Similar Messages
-
Help in solving this pl/sql block
Hi
Could some one help me in solving my problem
i want some data to be extracted by a sql its not fetching it so i prefered to write a pl/sql block for it ...
the block is as follows
begin
cursor opunit is
select code from fmg_operating_units;
cursor pak_code is --- those are the 3 codes which i require
select 'BNL' from dual
union select 'HNA' from dual
union select 'HNL' from dual;
cursor data1(opunit,pak_code) is
select mas.name ,
cl.id ,
opup.oun_code ,
fmg_phone_no(mas.id),
clpk.pak_code ,
clpk.id
from fmg_op_unit_positions opup,
fmg_clients cl,
fmg_client_paks clpk,
fmg_masters mas,
fmg_policies po,
fmg_policy_items pi
where mas.id=cl.mas_id
and cl.id=clpk.cli_id
and clpk.oup_id=opup.id
and opup.oun_code = opunit
and clpk.id=po.ctp_id
and po.id=pi.pol_id
and pi.current_status='AC'
and clpk.pak_code = pak_code;
loop opunits
loop pak_code
open data1
fetch data1(opunit,pak_code) ;
end loop;
end loop;
could some one help me in extracting the data and put it on the CSV file ...
i would be very thank full to you if some one take some time to full fill this task..
thanks in advanceDeclare
cursor opunit is
select distinct code
from fmg_operating_units;
cursor pak_code is --- those are the 3 codes which i require
select 'BNL' codes from dual
union
select 'HNA' codes from dual
union
select 'HNL' codes from dual;
cursor data1(opunit,pak_code) is
select mas.name ,
cl.id ,
opup.oun_code ,
fmg_phone_no(mas.id),
clpk.pak_code ,
clpk.id
from fmg_op_unit_positions opup,
fmg_clients cl,
fmg_client_paks clpk,
fmg_masters mas,
fmg_policies po,
fmg_policy_items pi
where mas.id = cl.mas_id
and cl.id = clpk.cli_id
and clpk.oup_id = opup.id
and opup.oun_code = opunit
and clpk.id = po.ctp_id
and po.id = pi.pol_id
and pi.current_status= 'AC'
and clpk.pak_code = pak_code;
begin
FOR opunits IN opunit LOOP
FOR pak_codes IN pak_code LOOP
OPEN data1;
fetch data1(opunits.code,pak_codes.codes) ;
EXIT WHEN data1%NOTFOUND;
< Rest of your code here > -- You can insert processed data into a temp table &
-- extract data from that table afterwards via select statement
-- & saving the data in a .cvs file extension.
CLOSE data1;
END LOOP;
END LOOP;
<Some more code here if applicable>
EXCEPTION
<Exception handling code section here>
END; -
Solve this Dynamic sql problem
hi i am sending the table and the contents in the table and what i want from the table.
SQL> descr sswms_rule_components;
Name Null? Type
RULE_COMPONENT_ID NOT NULL NUMBER
RULE_COMPONENT_CODE NOT NULL VARCHAR2(30)
RULE_COMPONENT_NAME NOT NULL VARCHAR2(100)
ENABLED_FLAG NOT NULL VARCHAR2(1)
DB_TABLE VARCHAR2 (100)
DB_COLUMN VARCHAR2 (100)
DB_FUNCTION VARCHAR2(100)
WHERE_CLAUSE VARCHAR2 (2000)
FROM_CLAUSE VARCHAR2 (2000)
The table contains the following data
db_table
sswms_shipment_lines
wsh_carrier_ship_method --- the data inside the db_table column is a table
db_column
Ship to
Carrier_id
Where_clause
Oe_order_headers_all.header_id = sswms_shipment_lines.order_header_id
From_clause
Oe_order_headers_all, sswms_shipment_lines -- the data inside the From_clause is a table
Now my requirement is to build a dynamic sql in forms 6i.when I click the build sql it should update the sql
So --- I have to write a procedure --
Select db_table || . || db_column || ‘’ || group_key
---group_key is an alias
From db_table, From_clause
--- Here the logic should be
1. I should remove the commas from the “FROM_CLAUSE” column and check for duplicate values
2. i should check for duplicate values for the “DB_TABLE “ column
3. I should compare both the FROM_CLAUSE and DB_TABLE column for DUPLICATE VALUES
4. After doing this I should add the result to the “FROM” in the select statement
5.The table name should not be repeated from the "FROM"
I am expecting the code and a positive reply from you.I'm waiting for the code the last 10 minutes and none arrived. What's happening? Developers, do my work, please! (ironic sentence)
-
How to create a counter using Oracle SQL Developer?
Is there any way to create a counter using Oracle SQL Developer to create the below scenario. Meaning it will recorded down the name of user and ID and time and the date they login.
Library portal home statistics shows how many users (outside and within the campus) visit the library portal.
Page Access statistics is recorded on an hourly basis. Users may select the statistics by
yearly (statistics displayed by all months in the selected year)
monthly (statistics displayed by all days in the selected month)
daily (statistics displayed by all hours in the selected day)I'm giving here one basic post - hope this will solve your problem --
SQL>
SQL>
SQL> create table audit_info
2 (
3 usr varchar2(50),
4 log_time timestamp(6)
5 );
Table created.
SQL>
SQL>
SQL> create table err_log
2 (
3 log_cd varchar2(20),
4 log_desc varchar2(500)
5 );
Table created.
SQL>
SQL>
SQL> create or replace procedure ins_err(errcd in varchar2,
2 errnm in varchar2)
3 is
4 pragma autonomous_transaction;
5 begin
6 insert into err_log values(errcd,errnm);
7 commit;
8 end;
9 /
Procedure created.
SQL>
SQL>
SQL> create or replace procedure ins_aud(ud in varchar2,
2 unm in varchar2)
3 is
4 pragma autonomous_transaction;
5 begin
6 insert into audit_info values(ud,unm);
7 commit;
8 exception
9 when others then
10 ins_err(sqlcode,sqlerrm);
11 end;
12 /
Procedure created.
SQL>
SQL>
SQL>
SQL> create or replace trigger log_odsuser1
2 after logon on odsuser1.schema
3 begin
4 ins_aud('ODSUSER1',sysdate);
5 exception
6 when others then
7 ins_err(sqlcode,sqlerrm);
8 end;
9 /
Trigger created.
SQL>
SQL*Plus: Release 9.2.0.1.0 - Production on Tue Jun 12 12:21:09 2007
Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
Connected to:
Oracle9i Enterprise Edition Release 9.2.0.6.0 - 64bit Production
With the Partitioning, OLAP and Oracle Data Mining options
JServer Release 9.2.0.6.0 - Production
SQL>
SQL>
SQL>
SQL> set serveroutput on
SQL>
SQL>
SQL> select * from audit_info;
USR
LOG_TIME
ODSUSER1
12-JUN-07 12.00.00.00000000 AMHope this will solve your purpose.
Regards.
Satyaki De. -
How to check how this table is populated in PL/SQL
Hi,
This is based on assumption that it using a trigger , function or procedure to update this table tbl1
how can i find out how tbl1 is being updated ? do i check thru those "referenced by" ?
or it updating another table set off a trigger that updates tbl1A can i find out from tbl1's details i.e those referenced by ?
pld advise as i do not know how tbl1 is being populated with certain data
tks & rdgsDependencies can help only if table populated with static SQL, placed in stored procedures.
Any kind of dynamic SQL or direct SQL-calls from client can't be tracked in such manner.
But You can try to query V$SQL in order to find exact statements modifying table.
My favorite way to solve such issues - SQL*Trace. -
MDB / AQ / RA problem: message not dequeued when put by PL/SQL to AQ
I’m facing the following problem: I have a setup a J2CA Resource Adapter for AQ (OEMS) and a MDB listener. As polling configuration I use the following:
<config-property>
<config-property-name>ListenerThreadMaxPollInterval</config-property-name>
<config-property-value>250</config-property-value>
</config-property>
According to the spec, this configuration should make sure that the underlying the JMS implementation polls the queue (AQ) every 250 ms in order to check whether there are available message.
When I send a message to the AQ using JMS, the message is dequeued within an acceptable time range.
However, when PL/SQL code enqueues messages directly to the AQ things do not work well:
1. When PL/SQL posts a message > 4096 kb (according to the spec messages > 4096 kb have to be posted in a different way, since a CLOB column is used) for the first time it takes about 4 minutes until the MDB picks it up. All subsequent messages are picked up immediately, which is not surprisingly since the documentation mentions that an adaptive strategy is used. 4 minutes is not acceptable for me.
2. When PL/SQL posts a message < 4096 kb the message expires on the AQ-queue (even though it is a non-expirable message), without being picked up by the MDB.
What do I do wrong? Help is needed and appreciated!With great pleasure I can announce 'a' solution for the problem stated. Apparently the JMS implementation expects certain JMS headers in the Oracle AQ message in order to fetch it from the AQ properly. The PL/SQL code, which caused the problem described in this post, looked like this:
declare
enqueue_options SYS.DBMS_AQ.enqueue_options_t;
message_properties SYS.DBMS_AQ.message_properties_t;
message_handle RAW (16);
user_prop_array SYS.aq$_jms_userproparray;
AGENT SYS.aq$_agent;
header SYS.aq$_jms_header;
MESSAGE SYS.aq$_jms_text_message;
p_xml_intern_bericht varchar2(8000);
p_len_message number;
begin
--p_xml_intern_bericht :='bla';
p_xml_intern_bericht :='test';
p_len_message := LENGTH (p_xml_intern_bericht);
dbms_output.put_line('->' ||p_len_message);
IF p_len_message > 4000
THEN
MESSAGE := SYS.aq$_jms_text_message (header,p_len_message,NULL,p_xml_intern_bericht);
ELSE
MESSAGE :=SYS.aq$_jms_text_message (header,p_len_message,p_xml_intern_bericht,NULL);
END IF;
DBMS_AQ.enqueue (queue_name => 'MY_AQ' ,
enqueue_options => enqueue_options,
message_properties => message_properties,
payload => MESSAGE,
msgid => message_handle
COMMIT;
end;
After adding the required JMS headers as in the snipped below, the message was picked up immediately from the AQ:
declare
msg SYS.AQ$_JMS_TEXT_MESSAGE;
msg_hdr SYS.AQ$_JMS_HEADER;
msg_agent SYS.AQ$_AGENT;
msg_proparray SYS.AQ$_JMS_USERPROPARRAY;
msg_property SYS.AQ$_JMS_USERPROPERTY;
queue_options DBMS_AQ.ENQUEUE_OPTIONS_T;
msg_props DBMS_AQ.MESSAGE_PROPERTIES_T;
msg_id RAW(16);
dummy VARCHAR2(4000);
begin
msg_agent := SYS.AQ$_AGENT('', null, 0);
msg_proparray := SYS.AQ$_JMS_USERPROPARRAY();
msg_proparray.EXTEND(1);
msg_property := SYS.AQ$_JMS_USERPROPERTY('JMS_OracleDeliveryMode', 100, '2', NULL, 27);
msg_proparray(1) := msg_property;
msg_hdr := SYS.AQ$_JMS_HEADER(msg_agent,null,'MY_SCHEMA',null,null,null,msg_proparray);
msg := SYS.AQ$_JMS_TEXT_MESSAGE(msg_hdr,null,null,null);
msg.text_vc := 'test';
msg.text_len := length(msg.text_vc);
DBMS_AQ.ENQUEUE( queue_name => 'MY_AQ'
, enqueue_options => queue_options
, message_properties => msg_props
, payload => msg
, msgid => msg_id);
commit;
end;
This solution was posted in the following blog: http://technology.amis.nl/blog/?p=2384. The environment in this blog is a Oracle XE database. The writer gets an ERROR when posting a message without adding the described JMS headers (see first pl/sql code snippet). Therefore he was forced to provide them in order to make AQ work for him.
The remarkable thing is that in our environment (Oracle 10.2.0.x) posting messages without the necessary JMS headers do not result in errors. The AQ accepts them but the JMS listener remains silent or receives them after an unacceptable amount of time.
This must definitely be a bug. Hope this information can help you to solve your PL/SQL AQ JMS problem. -
Can I use multiline SQL commands in a query (within a component)?
I would like to modify the following query:
<td>ItranslationString</td>
<td>
INSERT INTO TRANSLATIONSTRINGS (daKey, daLanguage, daTranslation, daStringFlag, daSourceFile) VALUES (?, ?, ?, 'N', ?)
</td>
<td>daKeyField varchar
daLanguageField varchar
daTranslationField varchar
StringTranslationFilename varchar
</td>
so that the daSourceFile a) is selected from another record, if it exists b) uses the constant, if not.
In SQL Command the commands (without placeholders) look:
declare c integer;
res varchar(30);
key_var varchar(100);
def_lang_var varchar(5);
begin
key_var := 'newString';
def_lang_var := 'en';
res := 'ap_string.htm';
select count(*) into c FROM TRANSLATIONSTRINGS WHERE daKey = key_var AND daLanguage = def_lang_var;
if c > 0 then
select daSourceFile into res FROM TRANSLATIONSTRINGS WHERE daKey = key_var AND daLanguage = def_lang_var;
end if;
INSERT INTO TRANSLATIONSTRINGS (daKey, daLanguage, daTranslation, daStringFlag, daSourceFile) VALUES (key_var, 'cs', 'translation', 'N', res);
end;
However, such a query does not work in the query resource (multiline commands cannot be used?).
Neither can I think of one line query that would provide the same functionality (tried to test with COALESCE).Yes, I got the point. The query looks like:
INSERT INTO TRANSLATIONSTRINGS (daKey, daLanguage, daTranslation, daStringFlag, daSourceFile)
SELECT daKey, daLanguage, daTranslation, daStringFlag, daSourceFile FROM (
select 'newString1' daKey, 'en' daLanguage, 'transl' daTranslation, 'N' daStringFlag, daSourceFile FROM TRANSLATIONSTRINGS WHERE daKey = 'newString1' AND daLanguage = 'cs' UNION ALL SELECT 'newString1' daKey, 'en' daLanguage, 'transl' daTranslation, 'N' daStringFlag, 'default' daSourceFile FROM DUAL)
WHERE rownum<=1;
so that's the way how to solve it via SQL.
(Since I can't use DECLARE, I need to bind entry parameters as many times as they appear in the query - not a very nice way, but it works).
The question still is, whether there is a way how to use a multiline query in Component Queries. Even though it is not mentioned specifically in the documentation, it seems it is NOT to be possible by design. So the real question is really WHY - I guess it would be a little bit more convenient to begin/commit transactions, use variables, etc. in a multiline query.
Yet, Sam, thanks! -
Hi ABAP Gurus,
Please help me in solving following ABAP SQL doubt.
In the table Zonfig there are two fields: FNAME and REQFLAG
FNAME.....REQFLAG
S1...........X
S2...........X
S3..........._
S4...........X
Other table T_Zconfig has one field : XNAME
XNAME
S1
S3
Now I have to select REQFLAG from Zconfig table for the values of field XNAME in T_Zconfig table.
That is in this case for FNAME S1 and S2 in Zonfig I need to fetch REQFLAG since in XNAME in T_Zonfig we just have S1 and S2.
Points will be surly awarded...
Thanks.Hi ABAP Gurus,
Please help me in solving following ABAP SQL doubt.
In the table Zonfig there are two fields: FNAME and REQFLAG
FNAME.....REQFLAG
S1...........X
S2...........X
S3..........._
S4...........X
Other table T_Zconfig has one field : XNAME
XNAME
S1
S3
Now I have to select REQFLAG from Zconfig table for the values of field XNAME in T_Zconfig table.
That is in this case for FNAME S1 and S3 in Zonfig I need to fetch REQFLAG since in XNAME in T_Zonfig we just have S1 and S3.
Points will be surly awarded...
Thanks. -
sql server services give error the remote procedure call failed [0x800706be] in sql server 2008.
To resolve this issue, I executed the following mofcomp command in command prompt to re-register the *.mof files:
mofcomp.exe "C:\Program Files (x86)\Microsoft SQL Server\100\Shared\sqlmgmproviderxpsp2up.mof".
but it does not work.
Plz give the exact soln to solve this error.sql server services give error the remote procedure call failed [0x800706be] in sql server 2008.
To resolve this issue, I executed the following mofcomp command in command prompt to re-register the *.mof files:
mofcomp.exe "C:\Program Files (x86)\Microsoft SQL Server\100\Shared\sqlmgmproviderxpsp2up.mof".
but it does not work.
Plz give the exact soln to solve this error.
So when you tried starting SQL server service it gave the error right ? or when you click on SQL server services in SQL server configuration manager(SSCM) you get this error. Can you be more clear. As far as I read your question it has something
to do with permission. Close SSCM window and this time right click on SQL server configuration manager and select run as administrator and check if you can see SQL server services
Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it
My Technet Articles -
Hi, i was venturing out to design an algorithm to generate sudoku puzzles, I was thinking of emplying 2D Matrix arrays. The idea I have is filling up the whole grid first with a solution then taking away a few numbers. I don't really know how to do this, though I have an idea, getting it to check the rows and columns add up to 45 and each 3x3 grid adds up to 45, 45 being the sum of all the numbers in a 3x3 grid. Would anyone be able to tell me if this would work and how would I be able to program this in JAVA. Many thanks in advance.
And I need an algorithm to solve sudokupuzzles.
That's the hard part, at least if you want to solve
it without brute force.Indeed, I thought that only with brute force Sudoku can be solved.
Indeed, I don�t think that there is a "magic intelligent" algorithm that can solve it . Well, Sudoku is cool exactly because it can just be solved by brute force. LOL!!!!
Maybe some math genius person knows how to write an algorithm to solve Sudoku easily, or how to explain and prove mathematically that an algorithm to solve that is not possible. -
Hi
I want to develop a Java program to solve Sudoku puzzles
My program must be able to:
�Read in a puzzle (from the predefined file format � see below)
�Display the unsolved puzzle
�Solve the puzzle
�Display the solved puzzle
File Format
The file consists of a number of integers.
The first integer signifies the size of the puzzle e.g. a 2 indicates a 4x4 puzzle, a 3 indicates a 9x9 puzzle, a 4 indicates a 16x16 puzzle and so on.
The remaining numbers are one integer for each square of the puzzle (e.g. 81 integers for a 9x9 puzzle) and should be read left to right and top row to bottom row. A zero means that the square is empty. A non-zero indicates the number in that square.> Hi
I want to develop a Java program to solve Sudoku
puzzles
My program must be able to:
non-zero indicates the number in that square.
And your question is? -
Complete newcomer to java!!
I want to create a sudoku java game using a gui. How do i go about this?? Whats the best way to start??Check this site for core java code to solve sudoku:
http://kulandai.blogspot.com/2006/10/sudoku-puzzle-java-source.html -
I'm looking for Algorithms that will solve sudoku puzzles. Im trying to write my own program for this to get ready for a compition. Would anyone know where to find these algorithms or ways to slove sudoku puzzles using a system every time? Any suggestions are helpfull thank you,
CobbwebI think you are going to have to write your own algorythm for this.
The math is beyond me, but off the bat I am going to guess that a brute-force-from-zero approach is not going to work anytime this century. However, if you make an initial elimination pass and then start trying possibilities with recursive elimination passes from there I bet it would chop things down enough that you could just do it that way without any really clever algorythm.
A B C
A 1 ? ?
B ? ? 3
C ? 2 ?With coordinates given as X,Y - so that the 3 is at C,B.
The number at A,B could be 1, 2, or 3, given only the rules of the game. Your "initial pass" is where you just run through the colum (A) and the row (B) and eliminate possibilities. So we know it cannot be 1 because there is a 1 at A,A and it cannot be 3 because there is a 3 at C,B. In a puzzle this simple that already tells us the answer (since only 1 is left) but obviously this will not be the case in a real puzzle. However, we will still have chopped out a LOT of possibilities.
Next we just pick an order for empty spaces - say left to right, top to bottom. The first one is B,A, so we go there. Then we just pick a number (moving from 1 up) to try out. That number gives us more information, so we make another pass over the entire grid eliminating stuff again. Then we just walk down the grid in a binary search tree type of dealy.
I bet that even a big puzzle would be no problem for a modern computer this way.
Drake -
Program using Native SQL ... Need suggestion.. Look into code
Hi Friends ,
I need your Inputs to solve the new requirement , which need to be solve using Native SQL,
For this i need to connet to data base 'SIP'.
The table used for this are SAPI.TRANSACTION
fields in SAPI.TRANSACTION
- SYSTEMCODE
- BATCH_ID
and more
the above two fields are selection parameters based on which i need to get data :
please rectify the code and also help me in this
TRY.
EXEC SQL.
CONNECT TO :'SIP'
ENDEXEC.
IF sy-subrc NE 0.
Error Message
ENDIF.
EXEC SQL.
OPEN dbcur FOR
SELECT SYSTEM CODE BATCH_ID
FROM SAPI.TRANSACTION
can i use where condition here , i tried to put the selection parameters here
and tried to put the internal table , but the programs gets terminated,
How should i get the fields from table SAPI.TRANSACTION
IF sy-subrc <> 0.
RAISE EXCEPTION TYPE cx_sy_native_sql_error.
ENDIF.
ENDEXEC.
DO.
EXEC SQL.
FETCH NEXT dbcur INTO :BATCH_ID
Here i want to get batch id and delete data from other table SAPI.BATCH
ENDEXEC.
IF sy-subrc <> 0.
EXIT.
ELSE.
ENDIF.
ENDDO.
EXEC SQL.
CLOSE dbcur
ENDEXEC.
EXEC SQL.
DISCONNECT :'SIP'
ENDEXEC.
ENDTRY.Hi Anirban, I tried that and it still gives the same error:
- "itab_mytable" cannot be a table, a reference, a string, or contain any of these objects. any of these objects"
itab_mytable has been declare as an internal table.
Basically, from the code in the link you gave me, I have made the following changes:
REPORT demo_native_sql.
TYPES: BEGIN OF st,
connid TYPE spfli-connid,
cityfrom TYPE spfli-cityfrom,
cityto TYPE spfli-cityto,
END OF st.
DATA: itab_mytable TYPE TABLE OF st.
<...>
EXEC SQL.
SELECT connid, cityfrom, cityto
INTO :itab_mytable
FROM spfli
ENDEXEC.
But this doesn't work. If the internal table is replaced with a one-lined work area, then the select statement works. -
Alright, I hate doing this, but I need some help...
Given is the following data in table 1:
ID
1
2
3
4
Now, ID 1 is connected with ID2, and ID3 is connected with ID4. This result is made by the following table, which shows the relationship cathesian style:
ID1 ID2 Connected
1 2 Y
1 3 N
1 4 N
2 3 N
2 4 N
3 4 Y
The challenge: I need a query to show the result of the output groups. In this case: 2 groups: 1 and 2 vs 3 and 4. The query needs to be build so that if we would have an ID 5 and 6 that don't have any connection, be taken into two new seperate groups...
I don't think the "CONNECT BY" statement would do the trick here, since all numbers are connected, not just the linked ones. It's just that the "Y" or "N" indicates their relationship...
Hope you guys can push me in the right direction... I've tried a lot :)
O by the way: it would be nice to solve this with SQL and not PLSQL because of performance issues.What are "normalized cartesian relations"?
Laurent solution may be correct if the OP data are transitively closed. If it is not, then you need to build transitively closed relation first, and the only way to accomplish that is leveraging "connect by" query.
For mathematically inclined, here is the essence of the problem: Given a binary relation R(x,y), first, build an equivalence relation out of it. Then identify each equivalence class with a distinct number. This subject is covered in chapter 6 of my book (http://www.bookpool.com/sm/0977671542). Here is an extract:
======================================================
With proper graph terminology the question can be formulated in just one line:
Find a number of connected components in a graph.
(The problem in the book counts the connected components, rather than identifies them).
Connected component of a graph is a set of nodes reachable from each other. A node is reachable from another node if there is an undirected path between them.
Figure 6.4: A graph with two connected components.
Reachability is an equivalence relation: it’s reflective, symmetric, and transitive. Given a graph, we formally obtain reachability relation by closing the Edges relation to become reflective, symmetric and, transitive (fig. 6.5).
Figure 6.5: Reachability as an equivalence relation: graph from fig. 6.4 symmetrically and transitively closed.
Returning back to the problem of finding the number of connected components, let’s assume that we already calculated the reachability relation EquivalentNodes somehow. Then, we just select a smallest node from each component. Informally,
Select node(s) such that there is no node with smaller label reachable from it. Count them.
Formally:
select count(distinct tail) from EquivalentNodes e
where not exists (
select * from EquivalentNodes ee
where ee.head<e.tail and e.tail=ee.tail
--------------------Soapbox----------------------
Equivalence Relation and Group By (cont)
In one of the chapter 1 sidebars we have attributed the incredible efficiency of the group by operator to its proximity to one of the most fundamental mathematical constructions – the equivalence relation. There are two ways to define an equivalence relation. The first one is leveraging the existing equality operator on a domain of values. The second way is defining an equivalence relation explicitly, as a set of pairs. The standard group by operator is not able to understand an equivalence relation defined explicitly – this is the essence of the problem, which we just solved.
Being able to query the number of connected components earned us an unexpected bonus: we can redefine a connected graph as a graph that has a single connected component. Next, a connected graph with N nodes and N-1 edges must be a tree. Thus, counting nodes and edges together with transitive closure is another opportunity to enforce tree constraint.
Now that we established some important graph closure properties, we can move on to transitive closure implementations. Unfortunately, our story has to branch here, since database vendors approached hierarchical query differently.
Message was edited by:
Vadim Tropashko
Maybe you are looking for
-
Keynote '09 ... Hang and closed
After open app Keynote '09 and click new or open old file. Application hang and close in a few minute everytime "Keynote quit unexpectedly" Problem Detail and System Configuration Process: Keynote [4465] Path: /Applications/iWork '09/Keynote.app/Cont
-
Newbie can't figure out how to play one song only.
So I just got up and running with my new iPod 80GB Video. I ripped 3 CDS of tunes to mp3's with iTunes and loaded them into the iPod and it plays but I can't figure out how to just play a single song, it always continues to the next song alphabetical
-
How to expose odata service for input parameter based procedure.
i have created one procedure in my schema. CREATE PROCEDURE TEST (in id varchar) AS BEGIN SELECT * FROM "table" WHERE "ID" = :id; END; and i am able to call the procedure from console. CALL "schema"."TEST"('1') my question is how to expose this proce
-
Aperture won't complete import
Aperture will import all photos without a problem, but when it reaches the last photo it hangs. Aperture doesn't become unresponsive, it just never completes the import. I've been having this problem off and on for a few weeks. I rebuilt my library w
-
Logic 8 on Macbook 2.0 ?
Hi all, can the new Macbook 2.0 run Logic 8 smoothly? Lets say with 5 synth plug ins. Or do I need the 2.4 version? Thanks, Tim.