# Help generating an array to a Sudoku game.

• 11-06-2013, 04:07 AM
quemagalletas
Help generating an array to a Sudoku game.
Hi, this is my first message in this forum, I'm not an native english, but I going to try to explain myself as a good as I can.

So, I want to make a sudoku game, and the table is done, but now I have a big problem, I tryed to do an array to contain the numbers of the solution, and these numbers need to be generate random.

Well, In simple words I need a function who choose correct random numbers to fit in a sudoku game.

I hope everyone understand me, some corrections of my english are allowed too xD

Thank you!
• 11-10-2013, 05:48 PM
jalarie
Making the basic array is fairly easy. Deciding which digits to display to make an easy, moderate, or difficult puzzle is MUCH harder!

I start with a puzzle that I copied (stole!) from the news-paper. Then I swap rows within the top, middle, or bottom third of the puzzle. Then swap some collumns in the left, middle, or right third of the puzzle. Then swap the top and bottom third or the left and right third. Then change all of the numbers to the next highest number with nine becoming zero. Repeat the mixing a few times, and there is a new puzzle!

By the way, I don't sell the resulting puzzle; it's only for my own enjoyment.
• 11-10-2013, 07:39 PM
\\.\
I don't even know how to play the game but assuming you have a grid type system...

A 2 dimensional array
Code:

```board = [     [ 0, 1, 2, 3],     [ 5, 6, 7, 8],     [ 9,10,11,12],     [13,14,15,16] ];```
board[3][3] will = 16
board[2][1] will = 10
board[0][0] will = 0

what are your number ranges for the random numbers? Doesn't each row and column need to add up to a certain figure?
• 11-10-2013, 09:14 PM
jalarie
Quote:

Originally Posted by \\.\
I don't even know how to play the game

Start with a 9x9 grid. Each row must contain the digits 1-9, each column must contain 1-9, and each of the nine 3x3 boxes must contain 1-9. Some of the 81 cells are already filled in by the person who made up this particular puzzle. You must fill in the rest.

The person who started this question wants to know how to create a new puzzle.
• 11-11-2013, 05:08 PM
\\.\
OK Jalarie, I am still none the wiser.

I have played a couple of games online.

One I think I am going to give a miss, don't see the fascination with the game TBH.
• 11-12-2013, 04:43 PM
007Julien
There is very difficult to build Sudoku grids (which simpler describe is a list of 81 digits, like the Gordon Royle list of 49,151 minimum sudokus).

Since, see the source of this page to discover a very interesting Sudoku board which allow to test very quickly a grid.
• 11-12-2013, 07:35 PM
\\.\
http://www.websudoku.com/

Might inspire you but remember that the guy who wrote this has copyright on it.
• 11-12-2013, 10:29 PM
wbport
I have a few minor tweaks to a program Guyon Roche wrote a few years back: sudoku.htm.
• 11-13-2013, 04:45 AM
quemagalletas

I wrote this sudoku code by myself thinking and thinking, and works good, but I have a problem I want to include divs with "contentEditable" but I want the user only can insert one number.

• 11-13-2013, 05:06 AM
\\.\
Use text inputs that are limited to a single character, apply CSS formatting to remove the border and alter the size of the input field and generally make it look like you want or need.
• 11-15-2013, 11:25 AM
Tcobb
Nevermind.
• 11-20-2013, 12:35 AM
Tcobb
Greetings--

Until I saw your posting I had never heard of Sodoku before. I think I may be addicted now. Your original problem of generating random puzzles began to bother me once I started playing. It was driving me crazy. Here is a solution for you. The function, when called, returns the puzzle in a 2D array. I hope it will be of some use to you.

Code:

```function suduko(){     var i,j, q, opt, row, spot, weak, current, tmp, badFlag; var scramble= function(arr){ //returns array in scrambled order     var i, len,obj,sorter, rnd, res;     obj = {};     sorter = [];     res = [];     len = arr.length;     i = 0;     while(i < len){         rnd = Math.random() + "";         if(obj[rnd]){             continue;         }         obj[rnd] = arr[i];         i++;         sorter.push(rnd);     }     sorter = sorter.sort();         for(i = 0; i < len; i++){         res.push(obj[sorter[i]]);     }     return res; } //================================= var join = function(a1, a2){ //joins two arrays but strains out duplicate values     var arr,  i, len, v;     arr = a1.concat(a2);     len = arr.length;     for(i = 0;i< len; i++){         v = arr.shift();         if(arr.indexOf(v) != -1){             continue;         }         arr.push(v);     }     return arr; } var getColumn = function(off){ //gets all values in the specified column     var i, arr, v;     arr = [];     for(i = 0; i < 9; i++){         v = q[i][off];         if(v != 0){             arr.push(v);         }     }     return arr; } var getRow = function(off){//gets all values in a row     var i, arr, v;     arr = [];     for(i = 0; i < 9; i++){         v = q[off][i];         if(v != 0){             arr.push(v);         }     }     return arr; } var invert =function(arr){ //gives all values that are NOT in the argument array     var i, res, b = [1,2,3,4,5,6,7,8,9];     b = scramble(b);     res = [];     for(i = 0; i < 9; i++){         if(arr.indexOf(b[i]) == -1){             res.push(b[i]);         }     }     return res; } var getGrid =function(col,row){ //gives all the current values in the 3X3 box to which it belongs     var res, i,j, v;     jmp = [0,3,6,9];     res = [];     col = Math.floor(col/3);     col = jmp[col];     row = Math.floor(row/3);     row = jmp[row];     for(i =row; i < (row + 3); i++){         for(j = col; j < (col + 3);j++){             v = q[i][j];             if(res.indexOf(v) == -1 && v != 0){                 res.push(v);             }         }     }     return res; } var getSet= function(c,r){  //get all current possible valid options for the position     var a, b, c;     a = getGrid(c,r);     b = getRow(r);     c = getColumn(c);     a = join(a,b);     a = join(a,c);     a =invert(a);     return a; }     var init = function(){ //build the 2D array and set all values to zero     var i, j;     q = [];     for(i = 0; i < 9; i++){         q[i] = [];         for(j =0; j < 9; j++){             q[i][j] = 0;         }     }    } //======== loop until the heuristic provides a valid puzzle do{     init();     opt = scramble([1,2,3,4,5,6,7,8,9]);     for(i = 0;i < 9; i++){         q[0][i] = opt[i];     }     opt = opt.slice(3,9);     opt = scramble(opt);         for(i = 0; i < 3; i++){         q[1][i] = opt[i];         q[2][i] = opt[(i + 3)];     }     badFlag = false;     for(row = 1; row < 9; row++){         while(1 == 1){             tmp = getRow(row);             if(tmp.length == 9){                 break;             }             weak = 10;             for(i = 0; i < 9;i++){                 if(q[row][i] != 0){                     continue;                 }                 tmp = getSet(i, row);                 if(tmp.length < weak){                     weak = tmp.length;                     spot = i;                 }             }             current = getSet(spot, row);             if(current.length == 0){  //heuristic failed--try again                 badFlag = true;                 break;             }             tmp = current.pop();             q[row][spot] = tmp;         }                 if(badFlag){             break;         }     } //end of row }while (badFlag);    //================== return q; } var c = suduko();  console.log(c);```
• 11-23-2013, 03:17 AM
Ayşe
Code:

```  <html> <head> <style type="text/css"> table { width:900px; height:700px;border:1px solid sandybrown; text-align:center;} td {  width:90px; height:50px; border:1px solid #ece; } .kutu1 { background-color:#ada;} .kutu2 { background-color:#aba;} .kutu3 { background-color:#eda;} .kutu4 { background-color:#ece;} .kutu5 { background-color:#def;} .kutu6 { background-color:#ebe;} .kutu7 { background-color:#aff;} .kutu8 { background-color:#efe;} .kutu9 { background-color:#caf;} input {display:inline;} </style> <script type="text/javascript"> // http://www.webdeveloper.com/forum/showthread.php?285909-Help-generating-an-array-to-a-Sudoku-game function yaz(bu) { var deger = bu.value; var idi = bu.parentNode.id; var A= idi.split(''); var tdmiz= document.getElementById(idi); tdmiz.innerHTML = deger; var harf = A[0]; var kolonNo  = A[1]; var tdEl, inp; for(var i=1; i< 10; i++) { tdEl= document.getElementById(harf+i);  inp= tdEl.getElementsByTagName('input'); for(var k=0; k<inp.length; k++){ if(inp[k].value==deger) { inp[k].style.display='none'; } } } var kolonHarf= ['a','b','c','d','e','f','m','h','k']; var cl, kolonhucre; for(var t=0; t<9; t++) { cl= document.getElementById(kolonHarf[t] + kolonNo); kolonhucre = cl.getElementsByTagName('input'); for(var u=0; u< kolonhucre.length; u++){ if(kolonhucre[u].value==deger) { kolonhucre[u].style.display='none'; } } } var N; if(A[1]<4 ) N = [1,2,3]; if(A[1]> 3 && A[1] < 7 ) N = [4,5,6]; if(A[1]>6) N = [7,8,9]; var H ; if(A[0] =='a' || A[0] =='b' || A[0]=='c') {H = ['a','b','c'];} if(A[0] =='d' || A[0] =='e' || A[0]=='f') {H = ['d','e','f'];} if(A[0] =='m' || A[0] =='h' || A[0]=='k') {H = ['m','h','k'];} var say, num,  kutu=[]; for(say =0; say< N.length; say++) { for(num=0; num < H.length; num ++) { if(A[0]!=H[say] && A[1] != N[num] ) { kutu[kutu.length]= H[say] + N[num]; } } } var r, grb, grbinp, numara; for(r =0; r<kutu.length; r++) { grb= document.getElementById(kutu[r]); grbinp= grb.getElementsByTagName('input'); for(numara =0; numara< grbinp.length; numara++) { if(grbinp[numara].value==deger) { grbinp[numara].style.display='none';} } } } </script> </head> <body> <div id="sudoku"></div> <script type="text/javascript"> var kutuNosu= [1,1,1,2,2,2,3,3,3]; var alfabe= ['','a','b','c','d','e','f','m','h','k']; var str='<table>'; for(var saymak=1; saymak <10; saymak++) { if(saymak >3 && saymak <7) { kutuNosu= [4,4,4,5,5,5,6,6,6];} if(saymak >6 && saymak <10) { kutuNosu= [7,7,7,8,8,8,9,9,9];} str += '<tr>'; for(var huc= 1; huc<10; huc++) { str += '<td class="kutu'+kutuNosu[huc-1]+'" id="'+alfabe[saymak]+huc+'">'; for(var but=1; but<10; but++) { str += '<input type="button" value="'+but+'" onclick="yaz(this)">'; } str +='</td>'; } str +='</tr>'; } str +='</table>'; var sud= document.getElementById('sudoku'); sud.innerHTML =str; </script> </body> </html>```
• 11-25-2013, 11:33 AM
007Julien
The problem is not to fill grid with permutations, but to fill partially grids to build valid Sudokus, with an unique solution ! Here is some functions with comments to test and build Sudoku grids...

Code:

```// Auxiliary functions function copyBoard(dest,src) {     for (var i=0;i<81;++i) dest.cells[i]=src.cells[i]; } function possiblesChoice(val){ var c=new Array,n=0;     for (var i=1;i<10;++i) if(val&(1<<i)) c[n++]=i;     return c; } function cellToString(d){     if (d&1) {for (var i=1;i<=9;i++) if ((d &(1<<i))!=0) return ""+i;}     return "0"; } /* ====== Bord constructor ======     Essentially an array of cells.     Each cell is an integer whose individual bits have the following meanings :     Rank 0 : 0 the cell is empty, the other ranks with the value 1, from 1 to 9, denote the possible values     Rank 0 : 1 the cell is full, the unique rank with the value 1 denote is value.     A leer cell take the value 1022 (2^10-1 => ten bits 1) with 9 bit to 1 and a 0     minChoiceCell : usefull to solve the grid with the minimum of tests */ function Board(){     this.cells=new Array();for (var i=0;i<81;i++) this.cells[i]=1022;     this.minChoiceCell=99; } with ({o:Bord.prototype}){     // Set the value v in the cell p and update the other cells     o.setValue=function(p,v) {         var k,v=1<<v,w=1023-v,x=p%9,y=Math.floor(p/9),r=Math.floor(x/3)*3,s=Math.floor(y/3)*3;         for (k=0;k<9;k++){this.cells[x+k*9]&=w;this.cells[k+y*9]&=w;         this.cells[r+(k%3)+9*(s+Math.floor(k/3))]&=w;}         this.cells[p]=v+1;     }     /* The Brain           Fill the cells in which a single solution is needed :         - an unique value possible for the cell         - an unique value possible in a row, col or region.       Return the minimum number of possibles choice in the cell minChoiceCell         except 11, if a cell can not take a value => Grid impossible     */     o.reduceBoard=function() {var i,m=10,o=99,v,w,x,y,r,s,rws=new Array(),cls=new Array(),sqr=new Array();         for (var i=0;i<9;++i) {rws[i]=0;cls[i]=0;sqr[i]=0;}         for (var i=0;i<81;++i) if (((w=this.cells[i])&1)==0) {             if ((w>>=1)==0) return 11;// a cell can not take a value             v=1;while (w&=w-1) v++;// Count  the possible values             // an unique value possible for the cell             if (v==1) {w=this.cells[i];while (((w>>=1)&1)==0) v++;                 this.setValue(i,v);return this.reduceBoard()}             if (v<m) {m=v;o=i} // Store the minChoiceCell             // We add all binaries integer (in row,col and region) like decimal (there is no cary)             x=i%9;y=Math.floor(i/9);r=Math.floor(x/3);s=Math.floor(y/3);             w=parseInt((this.cells[i]>>1).toString(2));             cls[x]+=w;rws[y]+=w;sqr[3*s+r]+=w;}         if (m!=10) {             // To fill an unique value possible in a row, col or region             for (var i=0;i<9;++i) {                 y=rws[i].toString();                 if (-1<(v=y.indexOf('1'))) {v=y.substr(v).length;w=1<<v;                     k=0;while ((this.cells[9*i+k]&w)!=w) k++;                     this.setValue(k+9*i,v);return this.reduceBoard()}                 x=cls[i].toString();                 if (-1<(v=x.indexOf('1'))) {v=x.substr(v).length;w=1<<v;                     k=0;while ((this.cells[9*k+i]&w)!=w) k++;                     this.setValue(9*k+i,v);return this.reduceBoard()}                 r=sqr[i].toString();s=3*(i%3)+27*Math.floor(i/3);                 if (-1<(v=r.indexOf('1'))) {v=r.substr(v).length;w=1<<v;                     k=0;while ((this.cells[9*Math.floor(k/3)+(k%3)+s]&w)!=w) k++;                     this.setValue(9*Math.floor(k/3)+(k%3)+s,v);return this.reduceBoard()}             }         }         this.minChoiceCell=o;         return m;     }     /* Make tests with new Grids if needed and count the different solutions       A global variable sdkSol is to define to store a copy*/     o.searchSols=function () {var m,v,w,i;         while ((v=this.reduceBoard())<10) {             m=possiblesChoice(this.cells[w=this.minChoiceCell]);             for (i=1;i<m.length;++i){                 var nb=new Board();                 copyBoard(nb,this);                 nb.setValue(w,m[i]);                 nb=nb.srchS();                 if (nb) return nb;}             this.setValue(w,m[0]);}         if (v==10) {             if (1<++numSol) return this;             copyBoard(sdkSol,this)}         return null;     } } // See the post 6 for use ...```

## X vBulletin 4.2.2 Debug Information

• Page Generation 0.12308 seconds
• Memory Usage 2,456KB
• Queries Executed 11 (?)
Template Usage (21):
• (4)bbcode_code_printable
• (1)bbcode_quote_printable
• (1)footer
• (1)gobutton
• (1)navbar_moderation
• (1)navbar_noticebit
• (2)option
• (1)spacer_close
• (1)spacer_open

Phrase Groups Available (3):
• global
• postbit
Included Files (19):
• ./global.php
• ./includes/class_bootstrap.php
• ./includes/init.php
• ./includes/class_core.php
• ./includes/config.php
• ./includes/functions.php
• ./includes/class_friendly_url.php
• ./includes/class_hook.php
• ./includes/class_bootstrap_framework.php
• ./vb/vb.php
• ./vb/phrase.php
• ./includes/functions_calendar.php
• ./includes/class_bbcode_alt.php
• ./includes/class_bbcode.php
• ./includes/functions_bigthree.php
• ./includes/functions_notice.php

Hooks Called (41):
• init_startup
• init_startup_session_setup_start
• database_pre_fetch_array
• database_post_fetch_array
• init_startup_session_setup_complete
• global_bootstrap_init_start
• global_bootstrap_init_complete
• cache_permissions
• fetch_foruminfo
• global_state_check
• global_bootstrap_complete
• global_start
• style_fetch
• global_setup_complete
• bbcode_fetch_tags
• bbcode_create
• bbcode_parse_start
• bbcode_parse_complete_precache
• bbcode_parse_complete
• cache_templates
• cache_templates_process
• template_register_var
• template_render_output
• fetch_template_start
• fetch_template_complete
• parse_templates