Question

sudoku in C

Asked by: errang

Hey,

       I got some pseudocode that I need to translate, I was just wondering if I could get some opinions to see if I got it right.

My main question is with the "UNION" part of this pseudocode... does it mean that they just want us to take the factorial of 9 to get the maximum value?

singleton is a function that returns true or false based on whether a bit is set.

This bit of code relies on a few other functions such as:
bit_count: This function takes an integer and returns the count of the
number of bits set.

get_nth_set_bit: This function takes an integer and an index; it iterates
through the bits of the integer (from LSB to MSB) counting set bits until
it comes to the indexth set bit. The current bit position is returned.

I got these functions figured out, and I know they work because they passed the tests.

Right now... I'm not 100% sure if I'm headed the right way, so some feedback on my translation would be appreciated =)

Thanks in advance!

<PSEUDOCODE>
changed = false
  for i in 1 to 9:
    for j in 1 to 9:
    value = board[i][j]
   
       if value is not a singleton:
     
       isum = UNION of board[k][j] for k in 1 to 9, where k ! = i
       if isum is not all possibilities:
       set board[i][j] to possibility not in isum
       changed = true
 
       jsum = UNION of board[i][k] for k in 1 to 9, where k!= j
       if jsum is not all possibilities:
       set board[i][j] to possibility not in jsum
       changed = true
    
       ksum = UNION of board[x][y] for each square in 3*3 square not including(i,j)
       if ksum is not all possibilities:
       set board[i][j] to possibility not in ksum
       changed = true
    endfor
endfor
 
<This is the semi C code I translated it to>
changed = false;
 
for(int i = 0; i<=9; i++){
   
   for(int j = 0; j<=9; j++){
 
      value = board[i][j];
      if(!(singleton(board[i]))||(singleton(board[j]))){
 
        isum = UNION of board[k][j] for k in 1 to 9, where k!=i
        if(isum != 45){
           board[i][j] = 45 - (isum + i); //To make sure that board != i and we get a # not in the array.
           changed = true;
        }
 
	jsum = UNION of board[i][k] for k in 1 to 9, where k!=j
        if(jsum != 45){
           board[i][j] = 45 - (isum + j); //To make sure that board != j and we get a # not in the array.
           changed = true;
        }
 
	ksum = UNION of board[x][y] for each square in 3*3 square not including (i,j)
        if(ksum != 45){
           board[i][j] = 45 - ksum; //To make sure we get a # not in the array.
           changed = true;
        }
 
    }
}

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-09-21 at 17:58:01ID24750299
Tags

sudoku

,

C

Topic

C Programming Language

Participating Experts
4
Points
500
Comments
25

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. pseudocode
    1)writte a pseudocode to accept to string from the user.Compare both of them and display a message indicating whether the string are equal or not. 2)how do we join two string.
  2. singleton basics
    hi experts, a simpe question : singleton design pattern: I just want some basic clarification about singleton design pattern. The below example shows the implimentation for singleton design pattern. For jdbc program, since loading the class drivers is expensive we just mak...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: ozoPosted on 2009-09-21 at 18:08:20ID: 25389015

If board[i][k] is represented by setting a different bit for each possibility, then you can implement union as the | of all the board values

 

by: errangPosted on 2009-09-21 at 18:30:13ID: 25389063

>>If board[i][k] is represented by setting a different bit for each possibility, then you can implement union as the | of all the board values

you mean like 1 || 2 || 3 ... || 9?

but wouldn't that just give 1 in the end?

 

by: ozoPosted on 2009-09-21 at 23:00:45ID: 25389897

|| and | are different operators in C

also, 3 and 9 both have two bits set, not one bit set

 

by: errangPosted on 2009-09-22 at 08:40:06ID: 25394098

Hm... | is the bit wise or? Then the maximum value it would give me is 9, right?

 

by: PaulCaswellPosted on 2009-09-22 at 10:40:02ID: 25395414

Knowing the game, the board is most likely to contain numbers, not bits.

I would suggest you read "singleton" as meaning "does not contain a number".

Also read "UNION" as something like "all numbers seen".

Play the game a few times. Among the rules there is "a row/column cannot contain the same number twice". That looks very much like "isum" and "jsum".

Paul

 

by: ozoPosted on 2009-09-22 at 17:42:09ID: 25399119

if "UNION" is going to be a common operation, then it may be worthwhile to use a representation for the
numbers contained in the board that makes that operation simple.
One representation that could make that operation simple, would be to store the numbers from 1 to 9 as
2**(number-1)
 

The maximum value that could be given as  the result of a bitwise or may depend on the possible values going into the bitwise or
9 | 6 == 15
1 | 2 | 4 | 8 | ... | 256 == 511


If you are familiar with bitwise or, bitwise and, etc.
then you may know some very simple implementations of functions like
bit_count

 

by: _phoenix_Posted on 2009-09-23 at 14:32:33ID: 25408166

if not, here is one table :)

This one works only for nibbles [0..F], however it's not difficult to create a function that will support a byte or a bigger int number.

here an example:

static const char bitCountTable[16] =
{
   0,
   1,
   1,
   2,
   1,
   2,
   2,
   3,
   1,
   2,
   2,
   3,
   2,
   3,
   3,
   4
};
 
char bitCount(char data)
{
   char result;
 
   result = bitCountTable[((data & 0xF0) >> 4)] + bitCountTable[data & 0x0F];
 
   return (result);
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:

Select allOpen in new window

 

by: errangPosted on 2009-09-23 at 16:05:26ID: 25408879

Thanks for the help so far =)

I need a bit more help with debugging this for "harder" sudoku boards, where we don't have as many numbers to help...

This code works for boards with a nice bunch of numbers, but it leaves a few squares unsolved when you don't give it enough numbers.

//GRID_SQUARED = 3 * 3;
//ALL_VALUES = (1<<GRID_SQUARED)-1
 
bool rule2() {
  bool changed = false;
  int isum=0, jsum=0, ksum=0;
  for (int i = 0 ; i < GRID_SQUARED ; ++ i) {  
    for (int j = 0 ; j < GRID_SQUARED ; ++ j) {
      //for every square, if the value is not a singleton, 
      int value = board[i][j];
      if (!singleton(value)) {
		
	//union of all values of same column different rows
	for (int k = 0 ; k < GRID_SQUARED ; ++ k) {
	  if (k != i)  
	    isum |= board[k][j];
	}
		  
	if (isum != ALL_VALUES) {
	  board[i][j] = isum ^ ALL_VALUES;
	  changed = true;
	}
		
	//union of all values of same row different cols		
	for (int k = 0 ; k < GRID_SQUARED ; ++ k) {
	  if (k != j) 
	    jsum |= board[i][k];
	}
		  
	if (jsum != ALL_VALUES){
	  board[i][j] = jsum ^ ALL_VALUES;
	  changed = true;
	}
		  
	//union of all values of 3x3 square not including (i,j)
	int ii = i;
	int jj = j;
	for (int k = ii ; k < ii + GRIDSIZE ; ++ k) {
	  for (int l = jj ; l < jj + GRIDSIZE ; ++ l) {
	    if ((k == i) && (l == j)) {
	      continue;
	    }
	    ksum |= board[k][l];
	  }
	}
		  
	if (ksum != ALL_VALUES){
	  board[i][j] = ksum ^ ALL_VALUES;
	  changed = true;
	}			
      }	
    }		
  }
  return changed;
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:

Select allOpen in new window

 

by: errangPosted on 2009-09-23 at 21:44:54ID: 25410139

Hm... i tried debugging this myself, I commented out the rows first... and then the columns, and then the square... and each and every time, I got the same result, is that supposed to happen? I understand that they are implementing the same logic, but they are given different number sets, so shouldn't the output be at least a little different?

 

by: errangPosted on 2009-09-23 at 21:53:41ID: 25410168

I'm sorry phoenix... just so I understand what u'r saying here:

>>bitCountTable[((data & 0xF0) >> 4)] + bitCountTable[data & 0x0F];

data wasn't assigned anything right?, so are you anding it with the size of the full sudoku board, and then bit shifting it by the size of the square?

And then adding the value in bitCountTable[data & 0x0F]?

 

by: _phoenix_Posted on 2009-09-23 at 23:31:40ID: 25410518

I just added the routine that ozo suggested for bit counting, it may help you with the sudoku board.

>> If you are familiar with bitwise or, bitwise and, etc.
>> then you may know some very simple implementations of functions like
>> bit_count

The function will count the number of bits present in a byte, i.e. if the value of data is 0xF9, the function will return 6, which is the number of bits in the value 0xF9.

The bitCountTable has the number of bits present in one nibble, from 0x00 to 0x0F, the function takes the MSN (Most Significant Nibble) and shift it right by 4 bits which will be the value of the higher nibble and adds the number of bits counted in the lower nibble.

Hope this helps to create your game, I have not reviewed in deep the program.

 

by: ozoPosted on 2009-09-23 at 23:45:32ID: 25410577

>>bitCountTable[((data & 0xF0) >> 4)] + bitCountTable[data & 0x0F];
This counts up to 8 bits.
If your design stores 9 different values in data as 9 different bits.
then your count may go up to 9

 

by: errangPosted on 2009-09-23 at 23:46:21ID: 25410583

>>The bitCountTable has the number of bits present in one nibble, from 0x00 to 0x0F, the function takes the MSN (Most Significant Nibble) and shift it right by 4 bits which will be the value of the higher nibble and adds the number of bits counted in the lower nibble.

wait... does that mean the number 4 has anything to do with the size of the sudoku board or not? Or is it because a nibble has 4 bits, and by shifting it by 4, you get the MSN?

If the second one is true... I'm not exactly sure how to scale that for the 9x9 sudoku board... I was thinking I could try shifting it 9 bits (because I thought 4 was the number of squares in the smaller square), and do it that way...

 

by: errangPosted on 2009-09-23 at 23:55:41ID: 25410616

Sorry, ozo's comment didn't show up when I posted my reply... so was I right in thinking that I had to shift the bits by 9?

 

by: ozoPosted on 2009-09-24 at 01:28:54ID: 25411067

shifting by 9 instead of 4 won't help unless you extend bitCountTable,
and if you extend bitCountTable, then you may not need to shift by 9,
unless data can hold 18 different bit values

 

by: ozoPosted on 2009-09-24 at 01:53:31ID: 25411168

Did you say in the original question that you already got the bit_count and  get_nth_set_bit functions figured out?
How did you implement them. and what happens if you use the functions that you got figured out?

I'd have to know more about how the functions that you have posted fit into the overall program to know whether a bitCount that works up to 9 would solve your problem,
but if you extend bitCountTable up to 31
and you changed the & 0xF0
then the bitCount routine might work for 9 bits,
But unless chars on your machine hold more than 8 bits, it wouldn't be a char function.

I''m not sure what that has to do with your problem, since I don't see you calling the bitCount function anywhere.

 

by: errangPosted on 2009-09-24 at 05:52:13ID: 25412757

This is what I've got for the other functions.

nt bit_count(int value) {
 int count = 0; //initialize count variable
 while (value != 0){  //check if n is 0.  If it is 0 then just return 0.
   if (value & 1)   //by ANDing n and 1 we check if the right most bit is 1.
     count++; //if the right most bit is 1 then increment count
   value = value >> 1;  //shifting n to right one bit gives us the
next bit to check.
 }
 return count;    //once we've gone through all of n, 0s would be
shifted in and the loop will end.
}

int get_nth_set_bit(int value, int index) {
 int position = 0, count = 0;
 while (count <= index){
   if (value & 1)
     count++;
   value = value >> 1;
   position++;
 }
 return (position - 1);
}

 

by: _phoenix_Posted on 2009-09-24 at 08:09:43ID: 25414146

int bit_count(int value) ->> It will definitely work for a Pentium without trouble :D... The one I posted is highly optimized, however as I said a Pentium processor will not complain about your function.

<<ozo>> unless you extend bitCountTable. I don't think you need to extend bit count table. You could create a int (16 bit) bit count, just need to consider 4 nibbles instead of 2.

it would be something like:

bitCountTable[((data & 0xF000) >> 12)] +
bitCountTable[ ((data & 0x0F00) >> 8)] +
bitCountTable[ ((data & 0x00F0) >> 4)] +
bitCountTable[data & 0x000F];          

In this case, data is 16 bit integer.

char bitCount(int data)
{
   char result;
 
   result = bitCountTable[((data & 0xF000) >> 12)] +
            bitCountTable[ ((data & 0x0F00) >> 8)] +
            bitCountTable[ ((data & 0x00F0) >> 4)] +
            bitCountTable[data & 0x000F];
 
   return (result);
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

Select allOpen in new window

 

by: ozoPosted on 2009-09-24 at 14:34:43ID: 25418227

>I don't think you need to extend bit count table. You could create a int (16 bit) bit count, just need to consider 4 nibbles instead of 2.
my comment was in reference to changing >>4 to >>9
that is not what you did.

 

by: _phoenix_Posted on 2009-09-24 at 15:13:50ID: 25418527

>> my comment was in reference to changing >>4 to >>9
Why would you change the shift from 4 to 9?... the function objective is to count the number of bits in a given data. Changing the shift from 4 to 9 will give you a bad result.

>> that is not what you did.
what I have understood here is that a bit count routine is needed. The last one I posted will work up to 16 bits.

>> but if you extend bitCountTable up to 31
and you changed the & 0xF0
then the bitCount routine might work for 9 bits,
But unless chars on your machine hold more than 8 bits, it wouldn't be a char function.

Normally char will be 8 bit long (this may change of course)... The last routine supports 16, and you need to count up to 9 bits... so it will work.

 

by: ozoPosted on 2009-09-24 at 15:44:53ID: 25418701

>> Changing the shift from 4 to 9 will give you a bad result.
As I said.

>> But unless chars on your machine hold more than 8 bits, it wouldn't be a char function.
again, we agree

 

by: _phoenix_Posted on 2009-09-24 at 15:46:41ID: 25418711

huh...

 

by: ozoPosted on 2009-09-24 at 16:34:39ID: 25418981

Both _phoenix_ and I agree that just to shift the bits by 9 instead of by 4 will not give a good result, and that
bitCount(char data) won't count up to 9 on many machines

 

by: epasquierPosted on 2009-09-24 at 22:14:36ID: 25420164

I see that this interesting problem is not closed. Do you still have a question ?
I'm afraid you have used thin both phoenix and ozo with the bit_count issue which was not the worst problem you had.

You should give them credit for their work, close this one and open a brand new topic with where you are in this task, to help us understanding your current problem
I have more than once told myself I should try tackle this sudoku solving algorithm (but C would not be my favorite choice there. Delphi might be a lot easier)

For the bit count , I assert you that phoenix solution is the right one. If you don't see why, don't bother with low-level functions and concentrate on higher ones, and trust experts. I have just added a loop, it's more elegant and can be scaled for wider use (32 bits) on other applications.

char bitCount(int data)
{
   char result=0;
 
   while(data)
   {
      result += bitCountTable[data & 0xF];
      data >>= 4;
   }
   return result;
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

Select allOpen in new window

 

by: errangPosted on 2009-09-24 at 22:40:22ID: 25420245

Yea, sorry, my code gets stuck when there are duplicates in rows/columns... But the way the program's setup, if nothing changes, the program says it failed. And the way the code is setup, we can't make it pick one and move on.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...