-
Notifications
You must be signed in to change notification settings - Fork 0
/
Matrix.txt
2722 lines (2280 loc) · 78.5 KB
/
Matrix.txt
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
- SprialPrint rotate nxn matrix in spiral order
- expression valid ({[]})
- count region of 1
int a[][] = {
{1, 1, 0, 0, 1},
{1, 0, 0, 1, 0},
{0, 0, 1, 0, 0},
{0, 0, 0, 0, 1},
{0, 0, 0, 0, 1}
};
output : 3 , count region of 1
- generic queue using stack
-cannibals and missionaries problem
-water jug problem
-delete duplicate rows from a table which does not have primary key or any unique value in any column
-exception handling in PL SQL
-The 8-puzzle
- solve sudoku
snake rem
demo.ATM
- program add/ subtract date without using java api
- 8 queens problem
- print heiarchy of ur organization from ceo to your position
- 8 stone are there in that 7 are same size and 1 is smaller , Identify this in minimum iteration
- binary to decimal conversion and vise versa
- http://howtodoinjava.com/2014/04/18/real-java-interview-questions-asked-for-oracle-enterprise-manager-project/
- why u want to join oracle
- if you join what benifite oracle can find from you
- why you want to leave other organization
- matrix manupulation, sorting in differrent ways rem
- queue, stack, link list implementation rem
- primary key foreign key composite key expain with practical example rem
- get past 6 months records from the data base make query ( mainly date conversation)
- swap the number without using 3rd temp variable
-hotel management process design rem
-library management process design rem
-jdbc
-demo.BFS
-Longest SubString
- removeDuplicates from array
-demo.StackSort
1. Sum of digit without using +, - and & operator.
2. Let Array be {1, 4, 45, 6, 10, -8} and sum of 2 digit from array to find be 16 (answer is 10 and 6, need to perform with only 1 loop)
3. find largest substitution using 2 characters from string (ex: Input: abdbcbcbcbbbda Output: bcbcbcbbb as it is largest string made by 2 characters only)
4. Check for balanced parentheses in an expression (Need to perform with 4 input characters (, ), [ and ]. Input: ()()[] -> Balanced, ()()[(] -> Unbalanced)
Difference between Array and ArrayList
About Current Company.
Current project, technology and architecture.
solution
****************************************************************************************************************************************
count region of 1
int a[][] = {
{1, 1, 0, 0, 1},
{1, 0, 0, 1, 0},
{0, 0, 1, 0, 0},
{0, 0, 0, 0, 1},
{0, 0, 0, 0, 1}
};
output : 3 , count region of 1
package practice;
/**
* Created by EZDI\haresh.p on 14/8/17.
*/
public class demo.CountRegionOf1 {
public static void main(String[] args) {
int a[][] = {
{1, 1, 0, 0, 1},
{1, 0, 0, 1, 0},
{0, 0, 1, 0, 0},
{0, 0, 0, 0, 1},
{0, 0, 0, 0, 1}
};
int cp[][] = {
{-1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1}
};
int count = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
System.out.print(cp[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
if (a[i][j] == 1 && cp[i][j] != 0) {
count++;
cp[i][j] = 0;
getNearCount(a, i, j , cp);
for (int k = 0; k < a.length; k++) {
for (int l = 0; l < a.length; l++) {
System.out.print(cp[k][l] + " ");
}
System.out.println();
}
}
}
}
System.out.println(count);
}
private static int getNearCount(int[][] a, int i, int j, int[][] cp) {
int result = 0;
for (int k = j; k < a.length; k++) {
if (a[i][k] == 1 ) {
if (cp[i][k] != 0) {
result = 1;
cp[i][k] = 0;
}
} else {
break;
}
}
for (int k = i; k < a.length; k++) {
if (a[k][j] == 1 ) {
if (cp[k][j] != 0) {
result = 1;
cp[k][j] = 0;
}
} else {
break;
}
}
for (int k = i + 1, p = j-1; k < a.length && p > 0; k++,p--) {
if (p>0 && a[k][p] == 1 ) {
if(cp[k][p] != 0){
result = 1;
cp[k][p] = 0;
}
} else {
break;
}
}
return result;
}
}
****************************************************************************************************************************************
cannibals and missionaries problem
package practice.Cannibals;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class demo.Main {
public static void main(String[] args) {
/*System.out.println("==== Missionaries and practice.Cannibals Problem ====");
System.out.println("Choose the search method: ");
System.out.println("\t 1. Breadth-first search");
System.out.println("\t 2. Depth-limited search");
System.out.print("\nType your choice and press ENTER: ");
String optionStr = null;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
optionStr = in.readLine();
} catch (IOException e) {
System.out.println("[ERROR] Fail to read the typed option.");
e.printStackTrace();
}
int option = Integer.parseInt(optionStr);*/
long startTime = Calendar.getInstance().getTimeInMillis();
int option=1;
State initialState = new State (3, 3, Position.LEFT, 0, 0);
switch(option) {
case 1:
executeBFS(initialState);
break;
case 2:
executeDLS(initialState);
break;
default:
System.out.println("[ERROR] Invalid search option.");
}
long endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("Total time taken by existing code " + (endTime - startTime));
}
private static void executeBFS(State initialState) {
BreadthFirstSearch search = new BreadthFirstSearch();
State solution = search.exec(initialState);
printSolution(solution);
}
private static void executeDLS(State initialState) {
}
private static void printSolution(State solution) {
if (null == solution) {
System.out.print("\nNo solution found.");
} else {
System.out.println("\nSolution (cannibalLeft,missionaryLeft,boat,cannibalRight,missionaryRight): ");
List<State> path = new ArrayList<State>();
State state = solution;
while(null!=state) {
path.add(state);
state = state.getParentState();
}
int depth = path.size() - 1;
for (int i = depth; i >= 0; i--) {
state = path.get(i);
if (state.isGoal()) {
System.out.print(state.toString());
} else {
System.out.print(state.toString() + " -> ");
}
}
System.out.println("\nDepth: " + depth);
}
}
}
package practice.Cannibals;
import java.util.ArrayList;
import java.util.List;
enum Position {RIGHT, LEFT}
public class State {
private int cannibalLeft;
private int missionaryLeft;
private int cannibalRight;
private int missionaryRight;
private Position boat;
private State parentState;
public State(int cannibalLeft, int missionaryLeft, Position boat,
int cannibalRight, int missionaryRight) {
this.cannibalLeft = cannibalLeft;
this.missionaryLeft = missionaryLeft;
this.boat = boat;
this.cannibalRight = cannibalRight;
this.missionaryRight = missionaryRight;
}
public boolean isGoal() {
return cannibalLeft == 0 && missionaryLeft == 0;
}
public boolean isValid() {
if (missionaryLeft >= 0 && missionaryRight >= 0 && cannibalLeft >= 0 && cannibalRight >= 0
&& (missionaryLeft == 0 || missionaryLeft >= cannibalLeft)
&& (missionaryRight == 0 || missionaryRight >= cannibalRight)) {
return true;
}
return false;
}
public List<State> generateSuccessors() {
List<State> successors = new ArrayList<State>();
if (boat == Position.LEFT) {
testAndAdd(successors, new State(cannibalLeft, missionaryLeft - 2, Position.RIGHT,
cannibalRight, missionaryRight + 2)); // Two missionaries cross left to right.
testAndAdd(successors, new State(cannibalLeft - 2, missionaryLeft, Position.RIGHT,
cannibalRight + 2, missionaryRight)); // Two cannibals cross left to right.
testAndAdd(successors, new State(cannibalLeft - 1, missionaryLeft - 1, Position.RIGHT,
cannibalRight + 1, missionaryRight + 1)); // One missionary and one cannibal cross left to right.
testAndAdd(successors, new State(cannibalLeft, missionaryLeft - 1, Position.RIGHT,
cannibalRight, missionaryRight + 1)); // One missionary crosses left to right.
testAndAdd(successors, new State(cannibalLeft - 1, missionaryLeft, Position.RIGHT,
cannibalRight + 1, missionaryRight)); // One cannibal crosses left to right.
} else {
testAndAdd(successors, new State(cannibalLeft, missionaryLeft + 2, Position.LEFT,
cannibalRight, missionaryRight - 2)); // Two missionaries cross right to left.
testAndAdd(successors, new State(cannibalLeft + 2, missionaryLeft, Position.LEFT,
cannibalRight - 2, missionaryRight)); // Two cannibals cross right to left.
testAndAdd(successors, new State(cannibalLeft + 1, missionaryLeft + 1, Position.LEFT,
cannibalRight - 1, missionaryRight - 1)); // One missionary and one cannibal cross right to left.
testAndAdd(successors, new State(cannibalLeft, missionaryLeft + 1, Position.LEFT,
cannibalRight, missionaryRight - 1)); // One missionary crosses right to left.
testAndAdd(successors, new State(cannibalLeft + 1, missionaryLeft, Position.LEFT,
cannibalRight - 1, missionaryRight)); // One cannibal crosses right to left.
}
return successors;
}
private void testAndAdd(List<State> successors, State newState) {
if (newState.isValid()) {
newState.setParentState(this);
successors.add(newState);
}
}
public int getCannibalLeft() {
return cannibalLeft;
}
public void setCannibalLeft(int cannibalLeft) {
this.cannibalLeft = cannibalLeft;
}
public int getMissionaryLeft() {
return missionaryLeft;
}
public void setMissionaryLeft(int missionaryLeft) {
this.missionaryLeft = missionaryLeft;
}
public int getCannibalRight() {
return cannibalRight;
}
public void setCannibalRight(int cannibalRight) {
this.cannibalRight = cannibalRight;
}
public int getMissionaryRight() {
return missionaryRight;
}
public void setMissionaryRight(int missionaryRight) {
this.missionaryRight = missionaryRight;
}
public void goToLeft() {
boat = Position.LEFT;
}
public void goToRight() {
boat = Position.RIGHT;
}
public boolean isOnLeft() {
return boat == Position.LEFT;
}
public boolean isOnRigth() {
return boat == Position.RIGHT;
}
public State getParentState() {
return parentState;
}
public void setParentState(State parentState) {
this.parentState = parentState;
}
@Override
public String toString() {
if (boat == Position.LEFT) {
return "(" + cannibalLeft + "," + missionaryLeft + ",L,"
+ cannibalRight + "," + missionaryRight + ")";
} else {
return "(" + cannibalLeft + "," + missionaryLeft + ",R,"
+ cannibalRight + "," + missionaryRight + ")";
}
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof State)) {
return false;
}
State s = (State) obj;
return (s.cannibalLeft == cannibalLeft && s.missionaryLeft == missionaryLeft
&& s.boat == boat && s.cannibalRight == cannibalRight
&& s.missionaryRight == missionaryRight);
}
@Override
public int hashCode() {
int result = cannibalLeft;
result = 31 * result + missionaryLeft;
result = 31 * result + cannibalRight;
result = 31 * result + missionaryRight;
result = 31 * result + (boat != null ? boat.hashCode() : 0);
return result;
}
}
package practice.Cannibals;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
// based on the breadth-first search algorithm present on the 3o Edition of the
// "Artificial Intelligence A Modern Approach".
public class BreadthFirstSearch {
public State exec(State initialState) {
if (initialState.isGoal()) {
return initialState;
}
Queue<State> frontier = new LinkedList<State>(); // FIFO queue
Set<State> explored = new HashSet<State>();
frontier.add(initialState);
int ifCondi=0;
while (!frontier.isEmpty()) {
State state = frontier.poll();
explored.add(state);
List<State> successors = state.generateSuccessors();
for (State child : successors) {
if (!explored.contains(child) /*|| !frontier.contains(child)*/) {
System.out.println("if condition statisfied count : " + ++ifCondi);
if (child.isGoal()) {
return child;
}
frontier.add(child);
}
}
}
return null; // failure
}
}
****************************************************************************************************************************************
-water jug problem
package practice;
import java.util.LinkedList;
/**
* Created by EZDI\haresh.p on 9/8/17.
*/
public class demo.TwoWaterJug {
private LinkedList<Integer> adj[];
public static void main(String[] args) {
int n = 3, m = 5, d = 4;
System.out.println("Minimum number of steps required is " + minSteps(m, n, d));
}
private static int minSteps(int m, int n, int d) {
// To make sure that m is smaller than n
if (m > n) {
int t = m;
m = n;
n = t;
}
// For d > n we cant measure the water
// using the jugs
if (d > n)
return -1;
// If gcd of n and m does not divide d
// then solution is not possible
if ((d % gcd(n, m)) != 0)
return -1;
// Return minimum two cases:
// a) Water of n litre jug is poured into
// m litre jug
// b) Vice versa of "a"
return min(pour(n, m, d), // n to m
pour(m, n, d)); // m to n
}
private static int min(int n, int m) {
return n <= m ? n : m;
}
private static int pour(int fromCap, int toCap, int d) {
int from = fromCap;
int step = 1;
int to = 0;
while (true) {
int temp = min(from, toCap - to);
to += temp;
from -= temp;
step++;
if (from == d || to == d) {
break;
}
if (from == 0) {
from = fromCap;
step++;
}
if (to == toCap) {
to = 0;
step++;
}
}
return step;
}
private static int gcd(int n, int m) {
if (m == 0) {
return n;
}
return gcd(m, n % m);
}
}
****************************************************************************************************************************************
-delete duplicate rows from a table which does not have primary key or any unique value in any column
DELETE FROM your_table
WHERE rowid not in
(SELECT MIN(rowid)
FROM your_table
GROUP BY column1, column2, column3);
****************************************************************************************************************************************
-exception handling in PL SQL
DECLARE
c_id customers.id%type := &cc_id;
c_name customerS.No.ame%type;
c_addr customers.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
END IF;
EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
****************************************************************************************************************************************
-The 8-puzzle
package practice.eightPuzzle;
import java.util.Arrays;
import java.util.Stack;
public class Board {
//public Board(int[][] blocks) construct a board from an N-by-N array of blocks
// (where blocks[i][j] = block in row i, column j)
//public int dimension() board dimension N
//public int hamming() number of blocks out of place
//public int manhattan() sum of Manhattan distances between blocks and goal
//public boolean isGoal() is this board the goal board?
//public Board twin() a board obtained by exchanging two adjacent blocks in the same row
//public boolean equals(Object y) does this board equal y?
//public Iterable<Board> neighbors() all neighboring boards
//public String toString() string representation of the board (in the output format specified below)
private final int[][] tiles;
private int size;
private int zeroCol;
private int zeroRow;
private int hamming;
private int manhattan;
public Board(int[][] blocks){
size = blocks.length;
tiles =new int[size][size];
for(int i = 0; i <size; i++){
for(int j = 0; j<size; j++){
this.tiles[i][j] = blocks[i][j];
if(tiles[i][j] == 0)
setZero(i,j);
}
}
}
private void setZero(int i, int j){
this.zeroRow = i;
this.zeroCol = j;
}
public int dimension(){
return size;
}
public String toString() {
int N = size;
StringBuilder s = new StringBuilder();
s.append(N + "\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
s.append(String.format("%2d ", tiles[i][j]));
}
s.append("\n");
}
return s.toString();
}
public int manhattan(){
int arrayPosition;
int tile;
manhattan = 0;
for(int i = 0; i <size; i++){
for(int j = 0; j<size; j++){
tile = tiles[i][j];
if(tile == 0)
continue;
arrayPosition = 1+ j +(i*this.size);
if(arrayPosition-tile == 0)
continue;
double ii = Math.floor(((double)(tile-1))/this.size);
double jj = (tile-1)%this.size;
manhattan += (Math.abs(i-ii)+Math.abs(j-jj));
//StdOut.println("Tile:" + tile + " [MOVES:"+ (Math.abs(i-ii)+Math.abs(j-jj))+"] | Offsets: i "+ Math.abs(i-ii) + " j "+ Math.abs(j-jj));
}
}
return manhattan;
}
public int hamming(){
int arrayPosition;
int tile;
int displaced =0;
for(int i = 0; i <size; i++){
for(int j = 0; j<size; j++){
tile = tiles[i][j];
if(tile ==0)
continue;
arrayPosition = 1+ j +(i*this.size);
if(tile != arrayPosition)
displaced++;
else
continue;
}
}
return displaced;
}
public boolean isGoal(){
int arrayPosition;
int tile;
for(int i = 0; i <size; i++){
for(int j = 0; j<size; j++){
if(i==size-1 && j == size -1)
continue;
tile = tiles[i][j];
arrayPosition = 1+ j +(i*this.size);
if(tile != arrayPosition)
return false;
}
}
return true;
}
private int[][]deepCopy(int[][] array){
int[][] copy = new int[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
copy[i][j] =array[i][j];
}
}
return copy;
}
public Board twin() {
int[][] twin = deepCopy(tiles);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (tiles[i][j] != 0 && tiles[i][j + 1] != 0 && j < (size - 1)) {
int swap = twin[i][j];
twin[i][j] = twin[i][j + 1];
twin[i][j + 1] = swap;
return new Board(twin);
}
}
}
return new Board(twin);
}
public boolean equals(Object y){
Board that = (Board) y;
if (y == null) return false;
if (this == y) return true;
if (this.getClass() != y.getClass()) return false;
if (that.size != this.size) return false;
return Arrays.deepEquals(this.tiles, that.tiles );
}
public Iterable<Board> neighbors(){
Stack<Board> boards = new Stack<Board>();
if(zeroRow > 0){
Board boardUP = new Board(swap(tiles,-1,0));
boards.push(boardUP);
}
if(zeroRow < size-1){
Board boardDown = new Board(swap(tiles,1,0));
boards.push(boardDown);
}
if(zeroCol > 0){
Board boardLeft = new Board(swap(tiles,0,-1));
boards.push(boardLeft);
}
if(zeroCol <size-1){
Board boardRight = new Board(swap(tiles,0,1));
boards.push(boardRight);
}
return boards;
}
public int[][] swap(int[][] board, int rowOffset, int colOffset){
int[][] tempBoard = deepCopy(board);
tempBoard[zeroRow][zeroCol]= tiles[zeroRow+rowOffset][zeroCol+colOffset];
tempBoard[zeroRow+rowOffset][zeroCol+colOffset]=0;
return tempBoard;
}
}
package practice.eightPuzzle;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class Solver {
//public Solver(Board initial) // find a solution to the initial board (using the A* algorithm)
//public boolean isSolvable() // is the initial board solvable?
//public int moves() // min number of moves to solve initial board; -1 if no solution
//public Iterable<Board> solution() // sequence of boards in a shortest solution; null if no solution
//public static void main(String[] args) // solve a slider puzzle (given below)
// you will want to use comparator for hamming & man
//MinPq<node> pq as the priority queue
private demo.Node goalNode;
private Queue<demo.Node> pq = new LinkedList<>();
private Queue<demo.Node> pqTwin = new LinkedList<demo.Node>();
public class demo.Node implements Comparable<demo.Node>{
public Board board;
public demo.Node previous;
public int moves;
public int compareTo(demo.Node that){
//StdOut.println("i:" + this.priority() + " j:" + that.priority() + " "+ ((this.priority() > that.priority()) ? 1 : -1));
if(this.priority() == that.priority()) return 0;
return (this.priority() > that.priority()) ? 1 : -1;
}
public demo.Node(Board b, demo.Node prev, int m){
board = b;
previous = prev;
moves = m;
}
public int priority(){
return board.manhattan() + moves;
}
}
public Solver(Board initial){
Board initialBoard;
Queue<Board> neighbors = new LinkedList<>();
initialBoard = initial;
demo.Node currentNode = new demo.Node(initial, null, 0);
demo.Node currentTwin = new demo.Node(initial.twin(), null, 0);
pq.add(currentNode);
pqTwin.add(currentTwin);
while(!currentNode.board.isGoal() && !currentTwin.board.isGoal()){
currentNode = pq.poll();
currentTwin = pqTwin.poll();
for(Board b : currentNode.board.neighbors()) {
if(!b.equals(currentNode.board))
pq.add(new demo.Node(b, currentNode, currentNode.moves +1));
}
for(Board b : currentTwin.board.neighbors()) {
if(!b.equals(currentNode.board))
pqTwin.add(new demo.Node(b, currentTwin, currentTwin.moves +1));
}
}
if(currentNode.board.isGoal())
goalNode = currentNode;
else
goalNode = currentTwin;
}
public Stack<Board> solution(){
Stack<Board> trace = new Stack<>();
trace.push(goalNode.board);
while (goalNode.previous != null){
goalNode = goalNode.previous;
trace.push(goalNode.board);
}
return trace;
}
public boolean isSolvable(){
return goalNode != null;
}
public int moves(){
return goalNode.moves;
}
public static void main(String[] args) {
// create initial board from file
int[][] blocks = {
/*{1 ,2 ,3},
{0 ,5 ,6},
{7,8,4}*/
{0, 1 ,3},
{4 ,2 ,5},
{7 ,8 ,6}
};
Board initial = new Board(blocks);
// solve the puzzle
Solver solver = new Solver(initial);
// print solution to standard output
if (!solver.isSolvable())
System.out.println("No solution possible");
else {
System.out.println("Minimum number of moves = " + solver.moves());
Stack<Board> solution = solver.solution();
while (!solution.empty()){
System.out.println(solution.pop());
}
}
}
}
****************************************************************************************************************************************
- solve sudoku
public class demo.Sudoku {
// dimension of input
static int N = 9;
// sample input
static int grid[][] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, //
{ 5, 2, 0, 0, 0, 0, 0, 0, 0 }, //
{ 0, 8, 7, 0, 0, 0, 0, 3, 1 }, //
{ 0, 0, 3, 0, 1, 0, 0, 8, 0 }, //
{ 9, 0, 0, 8, 6, 3, 0, 0, 5 }, //
{ 0, 5, 0, 0, 9, 0, 6, 0, 0 }, //
{ 1, 3, 0, 0, 0, 0, 2, 5, 0 }, //
{ 0, 0, 0, 0, 0, 0, 0, 7, 4 }, //
{ 0, 0, 5, 2, 0, 6, 3, 0, 0 } };
/**
* Class to abstract the representation of a cell. Cell => (x, y)
*/
static class Cell {
int row, col;
public Cell(int row, int col) {
super();
this.row = row;
this.col = col;
}
@Override
public String toString() {
return "Cell [row=" + row + ", col=" + col + "]";
}
};
/**
* Utility function to check whether @param value is valid for @param cell
*/
static boolean isValid(Cell cell, int value) {
if (grid[cell.row][cell.col] != 0) {
throw new RuntimeException(
"Cannot call for cell which already has a value");
}
// if v present row, return false
for (int c = 0; c < 9; c++) {
if (grid[cell.row][c] == value)
return false;
}
// if v present in col, return false
for (int r = 0; r < 9; r++) {
if (grid[r][cell.col] == value)
return false;
}
// if v present in grid, return false
// to get the grid we should calculate (x1,y1) (x2,y2)
int x1 = 3 * (cell.row / 3);
int y1 = 3 * (cell.col / 3);
int x2 = x1 + 2;
int y2 = y1 + 2;
for (int x = x1; x <= x2; x++)
for (int y = y1; y <= y2; y++)
if (grid[x][y] == value)
return false;
// if value not present in row, col and bounding box, return true
return true;
}
// simple function to get the next cell
// read for yourself, very simple and straight forward
static Cell getNextCell(Cell cur) {
int row = cur.row;
int col = cur.col;
// next cell => col++
col++;
// if col > 8, then col = 0, row++
// reached end of row, got to next row
if (col > 8) {
// goto next line
col = 0;
row++;
}
// reached end of matrix, return null
if (row > 8)
return null; // reached end
Cell next = new Cell(row, col);
return next;
}
// everything is put together here
// very simple solution
// must return true, if the soduku is solved, return false otherwise
static boolean solve(Cell cur) {
// if the cell is null, we have reached the end
if (cur == null)
return true;
// if grid[cur] already has a value, there is nothing to solve here,
// continue on to next cell
if (grid[cur.row][cur.col] != 0) {
// return whatever is being returned by solve(next)
// i.e the state of soduku's solution is not being determined by
// this cell, but by other cells