Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by authurowen(m): 3:38pm On Jun 19, 2013 |
PRINT SPIRAL:
Write a code to print the following matrix in spiral Form. i.e. If I apply the following 4x4 matrix to your code
1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7
It should produce 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16.
N.B: Be Genuine in your solutions, Real S.E(s) are. |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by Javanian: 5:00pm On Jun 19, 2013 |
how is the test matrix going to be entered into the program? |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by Javanian: 7:11pm On Jun 19, 2013 |
public class Spiral { public static void main(String[] args) { int[][] matrix = new int[4][4]; matrix[0][0] = 1; matrix[0][1] = 2;matrix[0][2] = 3;matrix[0][3] = 4; matrix[1][0] = 12;matrix[1][1] = 13;matrix[1][2] = 14;matrix[1][3] = 5; matrix[2][0] = 11;matrix[2][1] = 16;matrix[2][2] = 15;matrix[2][3] = 6; matrix[3][0] = 10;matrix[3][1] = 9;matrix[3][2] = 8;matrix[3][3] = 7; for(int i=0; i<3; i++) System.out.print(matrix[0][i]); for(int i=0; i<3; i++) System.out.print(matrix[i][3]); for(int i=3; i>0; i--) System.out.print(matrix[3][i]); for(int i=3; i>0; i--) System.out.print(matrix[i][0]); for(int i=1; i<2; i++) System.out.print(matrix[1][i]); for(int i=2; i>0; i--) System.out.print(matrix[2][i]); } }
|
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by javadoctor(m): 1:33am On Jun 20, 2013 |
So How much do I get to do this? |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by authurowen(m): 5:19am On Jun 20, 2013 |
Javanian: how is the test matrix going to be entered into the program? The input will be an array. i.e. assume we have an array of size n by n in C#, it would look thus int[,] input = new int[n,n]; in Java, it would look thus int[][] input = new int[n][n]; Don't pay too much attention to how the input will be read but rather how the business logic of the solution should end up as. |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by authurowen(m): 5:23am On Jun 20, 2013 |
Javanian: public class Spiral { public static void main(String[] args) { int[][] matrix = new int[4][4]; matrix[0][0] = 1; matrix[0][1] = 2;matrix[0][2] = 3;matrix[0][3] = 4; matrix[1][0] = 12;matrix[1][1] = 13;matrix[1][2] = 14;matrix[1][3] = 5; matrix[2][0] = 11;matrix[2][1] = 16;matrix[2][2] = 15;matrix[2][3] = 6; matrix[3][0] = 10;matrix[3][1] = 9;matrix[3][2] = 8;matrix[3][3] = 7; for(int i=0; i<3; i++) System.out.print(matrix[0][i]); for(int i=0; i<3; i++) System.out.print(matrix[i][3]); for(int i=3; i>0; i--) System.out.print(matrix[3][i]); for(int i=3; i>0; i--) System.out.print(matrix[i][0]); for(int i=1; i<2; i++) System.out.print(matrix[1][i]); for(int i=2; i>0; i--) System.out.print(matrix[2][i]); } }
Your solution is not Object Oriented Focused. It is doing too many things on its own.. Think more like creating a class and having helper methods handling steps and states/ array index where the pointer finds it self at. There are no magic numbers, as we do not know that the value at matrix[2][1] is 16. The provided input was just to serve as a mere oracle or Positive Unit Test case for the expected result (thats is if the input specified above was provided) PLS Avoid using magic numbers. |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by authurowen(m): 5:25am On Jun 20, 2013 |
javadoctor: So How much do I get to do this? emm, The satisfaction that you have been able to solve this puzzle genuinely without any external help. This is not to prove to anyone that you are superior but rather an attempt to share and discuss programming knowledge to those that may not be as quite up to par as you may be (thats if you are up to par) 1 Like |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by WhiZTiM(m): 8:47am On Jun 21, 2013 |
Wheres the challenge here?? Lemme assume there is more attached to this that I dunno.... and answer based on my understanding frankly, I would never solve this problem in an OOP fashion. Except I know why I should. in C++ int i; std::vector<int> vec; while(cin >> i) vec.push_back(i); std::sort(vec.begin(), vec.end()); std::copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, " ");
In OOP: class A //a thin wrapper around int ...not needed for languages where every type is an object
class B; //1 dimensional aggregation of A with internal sorting methods;
class C; //2 dimentional aggregation of A.... or aggregation of B;
class D; //composition of C; and responsible for I/O
//for your example //Class D reads the input and feeds to C, C receives them as 4 arrays. and construct them with B; //class C will now have 4 arrays of B... //class D orders C to sort itself and make outputs ready //class C will order all 4 Bs to sort their internal arrays... //class C will now perform a merge sort from all 4 Bs into one big B. //class D prints
//...I still Don't understand the aim of your question in OOP:::: Here is my very stupid logic: If you have a continuous stream of matrices being thrown into your system and as output, you need regular sorted matrix of specific time intervals: ....if you tweak the above OOP snippet, it should be applicable to parallel systems where a thread/process/system PP1 is responsible for taking matrix input continously; *passes it to the input buffers of another PP2, ...PP2 picks them from the buffers into a priority_queue (i.e sorted) ...after a few secs, another PP3 may request sorted data from PP2, then, PP2 pushes its queued data to PP3.... OOP will be better than procedural here... |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by authurowen(m): 9:01pm On Jun 22, 2013 |
WhiZTiM: Wheres the challenge here?? Lemme assume there is more attached to this that I dunno.... and answer based on my understanding frankly, I would never solve this problem in an OOP fashion. Except I know why I should.
in C++
int i; std::vector<int> vec; while(cin >> i) vec.push_back(i); std::sort(vec.begin(), vec.end()); std::copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, " ");
In OOP:
class A //a thin wrapper around int ...not needed for languages where every type is an object
class B; //1 dimensional aggregation of A with internal sorting methods;
class C; //2 dimentional aggregation of A.... or aggregation of B;
class D; //composition of C; and responsible for I/O
//for your example //Class D reads the input and feeds to C, C receives them as 4 arrays. and construct them with B; //class C will now have 4 arrays of B... //class D orders C to sort itself and make outputs ready //class C will order all 4 Bs to sort their internal arrays... //class C will now perform a merge sort from all 4 Bs into one big B. //class D prints
//...I still Don't understand the aim of your question in OOP:::: Here is my very stupid logic: If you have a continuous stream of matrices being thrown into your system and as output, you need regular sorted matrix of specific time intervals: ....if you tweak the above OOP snippet, it should be applicable to parallel systems where a thread/process/system PP1 is responsible for taking matrix input continously; *passes it to the input buffers of another PP2, ...PP2 picks them from the buffers into a priority_queue (i.e sorted) ...after a few secs, another PP3 may request sorted data from PP2, then, PP2 pushes its queued data to PP3....
OOP will be better than procedural here... as much as you would like to think your solution is right (syntax wise may be yes), semanticaly no. What you have done in plane english is simply read all the inputs, sort them and output them back to the screen in a ascending manner (THIS IS NOT THE SOLUTION TO THE QUESTION). Another example would be: [T H Q P] [X W S O] [B C D E] [G A R K] The resulting output (after applying the right solution should be): T H Q P O E K R A G B X W S D C Your solution should pls respect the fact that the input is a N x N Array, so an Object Oriented Solution would definitely suffice. Thanks to every body for trying, we're all here to learn. |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by jacob05(m): 7:06am On Jun 23, 2013 |
Hmmm, cool. My solution coming soon. |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by WhiZTiM(m): 10:08am On Jun 23, 2013 |
authurowen:
as much as you would like to think your solution is right (syntax wise may be yes), semanticaly no.
What you have done in plane english is simply read all the inputs, sort them and output them back to the screen in a ascending manner (THIS IS NOT THE SOLUTION TO THE QUESTION).
Another example would be:
[T H Q P] [X W S O] [B C D E] [G A R K]
The resulting output (after applying the right solution should be): T H Q P O E K R A G B X W S D C
Your solution should pls respect the fact that the input is a N x N Array, so an Object Oriented Solution would definitely suffice.
Thanks to every body for trying, we're all here to learn.
ooops! My misunderstanding! I understand the problem now... Thanks for your clarification. I will put forward possible solutions after church. |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by jacob05(m): 12:07pm On Jun 23, 2013 |
<?php /* Author: Pyjac (facebook.com/pyjac) */
class Spiral{
private $masterArray= [];
public function addArray(array $array){ $this->masterArray[] = $array; }
public function getSpiral(){ $workingList = []; while (!empty($this->masterArray) ){ $workingList = array_merge($workingList,$this->popListTopArray()); $workingList = array_merge($workingList,$this->popLastArraysElement()); $workingList = array_merge($workingList,$this->popListLastArrayReversed()); $workingList = array_merge($workingList,$this->popFirstArraysElementReversed()); } return $workingList;
}
private function popFirstArraysElementReversed() { if(empty($this->masterArray)) return array(); $workingArray = []; foreach ($this->masterArray as &$array) { $workingArray = array_merge($workingArray,(array)array_shift($array)); } krsort($workingArray); return $workingArray; }
private function popListLastArrayReversed() { if(empty($this->masterArray)) return array(); $workingArray = []; $workingArray=array_pop($this->masterArray); krsort($workingArray); return $workingArray; } private function popListTopArray() { if(empty($this->masterArray)) return array(); return array_shift($this->masterArray); }
private function popLastArraysElement() { if(empty($this->masterArray)) return array(); $workingArray = []; foreach ($this->masterArray as &$array) { //$testArray = $array[0]; $workingArray = array_merge($workingArray,(array)array_pop($array)); } return $workingArray; } }
//Usage: $a = ['T','H','Q' ,'P']; $b = ['X', 'W' ,'S','O']; $c = ['B', 'C', 'D','E']; $d = ['G', 'A', 'R', 'K']; $spiral = new Spiral(); $spiral->addArray($a); $spiral->addArray($b); $spiral->addArray($c); $spiral->addArray($d); var_dump($spiral->getSpiral());
|
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by jacob05(m): 12:08pm On Jun 23, 2013 |
The Above can still be greatly improved sha... ... Thanks |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by jacob05(m): 12:43pm On Jun 23, 2013 |
Just Realise that it's meant to be written in Java or C# . ##awkward Moment |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by jboy01(m): 5:26pm On Jun 23, 2013 |
Thank you for the challenging question, I only got the linear arrangement using vb.net, still working on it get a solution. ( An still a newbie in vb.net) 1 Like |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by mkwayisi: 6:09pm On Jun 23, 2013 |
Hey kids. What's with you and "OOP"? OK, being an old fart, I'd like to present a solution in C just in case anyone wishes to learn something from it. Here is a complete program to do the stuff: #include <stdlib.h> #include <stdio.h> #include <string.h>
int main(void) { char ***matrix; int i, j, k, l, ix, jx, len, dir, size; char buf[16];
printf("Enter the size of your matrix: " ); fgets(buf, sizeof(buf), stdin); len = strlen(buf); if (buf[len-1] == '\n') buf[len-1] = 0; if ((size = atoi(buf)) < 1) { printf("Error: Invalid input '%s'.\n", buf); return 1; } matrix = malloc(sizeof(char **) * size); if (matrix == NULL) { printf("Error: malloc failed." ); return 1; } for (i = 0; i < size; i++) { matrix[i] = malloc(sizeof(char *) * size); if (matrix[i] == NULL) { printf("Error: malloc failed." ); for (j = 0; j < i; j++) free(matrix[j]); free(matrix); return 1; } } for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { printf("Enter value for matrix[%d][%d]: ", i, j); fgets(buf, sizeof(buf), stdin); len = strlen(buf); if (buf[len-1] == '\n') { buf[len-1] = 0; len--; } matrix[i][j] = malloc(sizeof(char) * (len + 1)); if (matrix[i][j] == NULL) { printf("Error: malloc failed." ); for (; i >= 0; i--) { for (j--; j >= 0; j--) free(matrix[i][j]); free(matrix[i]); } free(matrix); return 1; } strcpy(matrix[i][j], buf); } } printf("\nThis is how your matrix looks like:\n" ); for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { printf("%s ", matrix[i][j]); } printf("\n" ); } printf("\nNow, here is the matrix in spiral order:\n" ); dir = 0; // 0 = R; 1 = D; 2 = L; 3 = U; i = 0, j = -1; for (len = size; len > 0; len--) { for (k = j < 0 ? 1 : 0; k < 2; k++, dir++) { switch (dir % 4) { case 0: ix = 0; jx = 1; break; case 1: ix = 1; jx = 0; break; case 2: ix = 0; jx = -1; break; case 3: ix = -1; jx = 0; break; } for (l = 0; l < len; l++) { i += ix; j += jx; printf("%s%s", !(i || j) ? "" : ", ", matrix[i][j]); } } } printf(".\n\n" ); for (i = 0; i < size; i++) { for (j = 0; j < size; j++) free(matrix[i][j]); free(matrix[i]); } free(matrix); return 0; }
1 Like |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by authurowen(m): 6:41pm On Jun 23, 2013 |
jacob05: <?php /* Author: Pyjac (facebook.com/pyjac) */
class Spiral{
private $masterArray= [];
public function addArray(array $array){ $this->masterArray[] = $array; }
public function getSpiral(){ $workingList = []; while (!empty($this->masterArray) ){ $workingList = array_merge($workingList,$this->popListTopArray()); $workingList = array_merge($workingList,$this->popLastArraysElement()); $workingList = array_merge($workingList,$this->popListLastArrayReversed()); $workingList = array_merge($workingList,$this->popFirstArraysElementReversed()); } return $workingList;
}
private function popFirstArraysElementReversed() { if(empty($this->masterArray)) return array(); $workingArray = []; foreach ($this->masterArray as &$array) { $workingArray = array_merge($workingArray,(array)array_shift($array)); } krsort($workingArray); return $workingArray; }
private function popListLastArrayReversed() { if(empty($this->masterArray)) return array(); $workingArray = []; $workingArray=array_pop($this->masterArray); krsort($workingArray); return $workingArray; } private function popListTopArray() { if(empty($this->masterArray)) return array(); return array_shift($this->masterArray); }
private function popLastArraysElement() { if(empty($this->masterArray)) return array(); $workingArray = []; foreach ($this->masterArray as &$array) { //$testArray = $array[0]; $workingArray = array_merge($workingArray,(array)array_pop($array)); } return $workingArray; } }
//Usage: $a = ['T','H','Q' ,'P']; $b = ['X', 'W' ,'S','O']; $c = ['B', 'C', 'D','E']; $d = ['G', 'A', 'R', 'K']; $spiral = new Spiral(); $spiral->addArray($a); $spiral->addArray($b); $spiral->addArray($c); $spiral->addArray($d); var_dump($spiral->getSpiral());
Thanks for attempting Jacob. (a PHP Solution is also feasible) but You solution should be better improved, as we do not know the size of the array until we're read it. so reading the input only 4 times will not suffice. |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by lordZOUGA(m): 6:56pm On Jun 23, 2013 |
this is trivial. you just have to print a 2 dimensional data structure in a different way. |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by danmc: 7:10pm On Jun 23, 2013 |
lordZOUGA: this is trivial. you just have print a 2 dimensional data structure in a different way. are you sure sir? i tried attempting it but couldn't do it. if it's trivia show us a solution (no offense) 1 Like |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by jacob05(m): 7:12pm On Jun 23, 2013 |
authurowen:
Thanks for attempting Jacob. (a PHP Solution is also feasible) but You solution should be better improved, as we do not know the size of the array until we're read it. so reading the input only 4 times will not suffice. You can add as much array to the list bro. An example to explain what you mean pls? |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by lordZOUGA(m): 7:13pm On Jun 23, 2013 |
danmc: are you sure sir? i tried attempting it but couldn't do it. if it's trivia show us a solution (no offense) no problem, after tonight's match. |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by jacob05(m): 7:14pm On Jun 23, 2013 |
lordZOUGA: this is trivial. you just have print a 2 dimensional data structure in a different way. your trivial solution will be much appreciated bro |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by danmc: 7:15pm On Jun 23, 2013 |
jacob05: You can add as much array to the list bro. An example to explain what you mean pls? he's saying make it dynamic so that it can handle any number of items in the matrix. what u have so far is static. anyway, it's good that u tried. |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by danmc: 7:17pm On Jun 23, 2013 |
lordZOUGA: no problem, after tonight's match. hmmm.. ok will be waiting. good luck 9ja |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by jacob05(m): 7:34pm On Jun 23, 2013 |
danmc: he's saying make it dynamic so that it can handle any number of items in the matrix. what u have so far is static. anyway, it's good that u tried. you can add as much arrays of any length with the addArray na. Or what again |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by WhiZTiM(m): 1:42am On Jun 24, 2013 |
Here is my code in python, well commented; and with very good explanation for easy comprehension.... #!/usr/bin/python """(C)24th June 2013, WhiZTiM contact: ionogu@acm.org twitter.com/ionogu facebook.com/onogu blog.whiztim.com PREAMBLE: this program transverse a square grid in spiral form... and its design is: nextMove() this function is the traveller... and it attempts to move up, right, down and left the grid it returns the successful move. """
def nextMove(x, y, state_grid, lst = 0): """ @param:x and @param:y This represents an (x,y) coordinate @param:state_grid: this is a mutuable grid of boolean values to indicate whether we have travelled to a coordinate, if not... we go according to @param:lst and set that coordinates travel-able value to False @param:lst: this helps to bring spiral transversal form to life.... Its values ranges from 0 to 3 and is used to make direction preference """ limit = len(state_grid[0]) #dimension of the square array """ 'first' is a preferential determiner, i.e if the while loop executes once without success, preference is reset to 0 and if there is still no success, it will break by the else clause """ first = True while(True): if(x-1 >= 0 and lst < 1): #1st preference: move left if(state_grid[x-1][y]): #if its visit-able state_grid[x-1][y] = False #then make it unvisit-able cause we are going to visit it lst = 0 #set preference to this direction return (True, (x-1), y, lst) #return turple if(y+1 < limit and lst < 2): #2nd preference: move up if(state_grid[x][y+1]): #similar as above state_grid[x][y+1] = False lst = 1 return (True, x, (y+1), lst) if(x+1 < limit and lst < 3): #3rd preference: move right if(state_grid[x+1][y]): #similar as above state_grid[x+1][y] = False lst = 2 return (True, (x+1), y, lst) if(y-1 >= 0 and lst < 4): #4th preference: move down if(state_grid[x][y-1]): #similar as above state_grid[x][y-1] = False lst = 3 return (True, x, (y-1), lst) if(first): #we will be here if we have tried preferences without success lst = 0 #lower or reset preference first = False #dont execute this block again else: break #free to execute the next one return (False, x, y, lst) #Finally failed! stop!!!
def readinput(): """ Read the space separated n * n elements from stdin Uses first line to automatically determine the size of the array """ first = True #tells us whether we are reading the first line n = 999999999L #number of lines, we assume the grids will never reach the square of this rtn = [] #return value. a 2D array(list) while(True): if(n == 0): break #if the last line has been read, break w = raw_input() #get raw_input() from stdin if(first): #if first line n = len(w.split()) #use the number of items to automatically determine #the number of lines to be read first = False #we are no more in the first line rtn.append(w.split()) #split the whitespace delimited elements in the line and append to return variable n -= 1 #we now need to read fewer lines return rtn
def main(): """ read input; setup variables for calling on the traveller ...till the traveller returns false """ array = readinput() # 't' represents the dimension of the array t = len(array[0]) # state_grid represents a 2D array(list) of boolean values all initialized to True # and its used for indicating whether a coordinate is visitable or not state_grid = [[True for i in range(t)] for i in range(t)] rtn = [] #holds return value x = 0 # 'x' or 'i'th dimension y = 0 # 'y' or 'j'th dimension lst = 0 #variable to indicate last direction of travel #we append the first item to our return, and set it's visit-able state_grid to False rtn.append(array[x][y]) state_grid[x][y] = False while(True): #next move returns a turple of types(bool, int, int, int) c, x, y, lst = nextMove(x, y, state_grid, lst) if not c: #test if there is no more move break #append results rtn.append(array[x][y]) #print answer print rtn
if(__name__ == "__main__": main() pass
http://pastebin.com/r3cMG9sM 1 Like |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by WhiZTiM(m): 1:53am On Jun 24, 2013 |
mkwayisi: Hey kids. What's with you and "OOP"? OK, being an old fart, I'd like to present a solution in C just in case anyone wishes to learn something from it. Here is a complete program to do the stuff:
How on earth do you want most people including rookies to learn that code!! when you wrote it as if you were contesting in Codeforces, CodeJAM, TopCoder and/or ACM-ICPC..... Next time. . . . explain whats going on there!! Well, I just went through your code and test-ran it.... I understand your code... you should have intelligently determined the size of the array based on the first line input! . . . manual entry of each element is too kid-like . . .(based on your "Hey kids" . good one though. 1 Like |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by WhiZTiM(m): 2:28am On Jun 24, 2013 |
my solution is uploaded on PasteBin... http://pastebin.com/r3cMG9sM...Well there are [size=24pt] 3 ways I know we could solve this[/size]. 1. Procedural/functional ...like my implementation 2. Object Oriented 3. Mathematically. 1You may have to be interested in Python to understand my code...(70lines uncommented, 122 lines commented) I was contemplating doing it in C++ or C# but thought it would be better in a lazy/weak typed language. **Ohkayy, I wouldnt talk on this cause all I would have said is represented VERY well in my Code 2OOP: this would be similar to number 1... but in this case, all items can be treated as objects by wrapping them in light weighted classes.. ---These objects should be aware of their relative positions in the coordinate ---These objects should contain a boolean property that signifies whether its been used or not ---An abstract object or pointer can be used to transverse through the instantiated objects.. ---there should exist a simple (up, down, left, right) traveller function that will persistently travel in one direction until it reaches a limit or an object that has been taken... in this case, it changes direction in a preferential manner... ---this continues in spiral direction until there is no more object to transverse ---THIS CAN ALSO be DONE RECURSIVELY ...easier 3MATHEMATICALLY: ...while I took a paper and was manually transversing through square matrices of diferent sizes... I realized that there exist this property of perfect squares:... ::: a summation of odd number sequences starting from 1 to n is equal to n^2. PROOF: if n = 3 1 + 3 + 5 = 9 if n = 5... 1 + 3 + 5 + 7 + 9 = 25 if n = 6 1 + 3 + 5 + 7 + 9 + 11 = 36 you can test for other cases ...now, assume a 5x5 grid.. A B C D E F G H I J K L M N O P Q R S T U V W X Y using n as 5, we have the following sequence... (1 + 3 + 5 + 7 + 9)... reversing it, we have (9, 7, 5, 3, 1)... the first L shape is of 9 elements... that is ... (A, B, C, D, E, J, O, T, Y)... the next L shape is of 7 elements... that is ... (X, W, V, U, P, K, F).... the next L shape is of 5 elements... that is ... (G, H, I, N, S) the next L shape is of 3 elements... that is ... (R, Q, L) and finally the last is (M)... [size=16pt]now... are you thinking mathematically....??[/size] yeah.... so, I did leave this method as a challenge to someone to implement authurowen's problem with MATHEMATICAL algorithm or discrete NUMERICAL algorithm.... "~~~Many programmers are really good, what may differentiate them is complex and subtle mathematical knowledge and skills~~~" ---says A renowned ACM-ICPC judge in Int'l Collegiate of Programming Contest....( I wish I recall the name) NB: I am not a mathematician but a maths hobbyist... 1 Like |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by kambo(m): 3:49am On Jun 24, 2013 |
------------------------------------------------------------------- Here's my solution. NLquiz.java (Test class) matrixPrinter.java (abstract class) spiralMatrixPrinter.java (implementing class) (C) nairaland.com/kambo ------------------------------------------------------------------------------ matrixPrinter.java --------------------------- //
public abstract class matrixPrinter { protected final String[][] grid; int Dim;//Dimension private int acceptedType=-1; //0 for int, 1 for char protected boolean locked=false; public matrixPrinter(final int dim) throws Exception { if(dim<0)throw new IllegalArgumentException("wrong dimension " Dim=dim; grid = new String[dim][dim]; for(int u=0;u<Dim;u++) for(int z=0;z<Dim;z++) grid[u][z]="";//init to negs } public void set(final int x,final int y,final char c) { if(x<0||x>=Dim||y<0||y>=Dim||locked) return; if(acceptedType==0)return; else { if(acceptedType==-1)acceptedType=1; grid[x][y]=String.valueOf(c); } } public void set(final int x,int y,int val) { if(x<0||x>=Dim||y<0||y>=Dim||locked) return; else { if(acceptedType>0)return; if(val<10&&val>=0) grid[x][y]=String.valueOf("0"+val); else grid[x][y]=String.valueOf(val); if(acceptedType==-1)acceptedType=0; } } public boolean allSet() { boolean ans=true; Outer: for(int y=0; y<grid.length;y++) for(int m=0; m<grid[y].length;m++) { if(grid[y][m]=="" {ans=false; break Outer;} } return ans; } public boolean isEmpty(){ boolean ans=true; Outer: for(int y=0;y<grid.length;y++) for(int x=0;x<grid.length;x++) { if(!grid[y][x].trim().equals("") { ans=false; break Outer; } } return ans; }
public void print(final String s){ System.out.print(s); System.out.print(" " }
public abstract void printGrid(); public final void actualLayout() { if(isEmpty())return; else { System.out.println(); for(int x=0;x<Dim;x++) { System.out.println(); for(int y=0;y<Dim;y++) {print(grid[x][y]); } } System.out.println(); } } }
------------------------------------------------------ spiralMatrixPrinter.java ------------------------------------------------------ // nairaland.com/kambo
public class spiralMatrixPrinter extends matrixPrinter { public spiralMatrixPrinter(final int Dim) throws Exception { super(Dim); }
public void printGrid() { // if(isEmpty())return; else { printer(0,grid.length-1); } } private void printer(final int s,final int max) { printer(s,max,1); } private void printer(final int start,final int maxIndex,int level) { if(start<0||maxIndex<0||maxIndex>=grid.length) { System.out.println(" arguments fail test returning.. : " //this method should throw an exception.. whatever.. } else { locked=true; //prevent data corruption.. int x=start; // x is a pointer for moving around the grid (the matrix) for(;x<=maxIndex;x++) print(grid[start][x]); // print top horizontal row //print vertical leftmost column x=start; x++; for(;x<=maxIndex;x++) print(grid[x][maxIndex]); //print bottom last row backwards. x=maxIndex; x--; for(;x>=start;x--) { print(grid[maxIndex][x]); } x=maxIndex; x--; //print rightMost column. for(;x>start;x--) { print(grid[x][start]); } System.out.print(" "
int start2=start; int maxI2=maxIndex; start2++; maxI2--; if(start2==maxI2) { //unlock access to data setting locked=false; //End case - the grid is an odd number length matrix. // print last cell. inner most cell print(grid[start2][maxI2]); return; } if(start2>maxI2) { //unlock locked=false; //end case - the matrix was even number length . return; } else printer(start2,maxI2,++level); } } } ---------------------------------------------------------------------------------------- NLquiz.java ----------------------------------------------------------------------------------------
// nairaland.com/kambo
// nairaland.com/kambo class NLquiz2 { public static void main(String ...s) throws Exception { int dim=1110; spiralMatrixPrinter sp = new spiralMatrixPrinter(dim); for(int x=0;x<dim;x++) for(int y=0;y<dim;y++) { //generate random numbers and feed em into the matrix printer int r = (int)((y*3)+ Math.random()*(x*y)); sp.set(x,y,r); } sp.actualLayout(); //print the initial array structure System.out.println(); sp.printGrid(); //print the spiral s tructure. } }------------------------------------------------------------------------------------------
NB: ----- Used an array of strings instead of integers for the sake of flexibility. the user could enter create two types of arrays , char arrays or integer arrays. - expect an "out of memory " type exception to be thrown for large arrays. - initializing the class constructor to take an array could be done but i dont matter - really. i went the longhand way of passing variables individually to the matrix cells. - I assume the array is balanced. not jagged and that all cells are filled with data. ------- |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by danmc: 5:09am On Jun 24, 2013 |
WhiZTiM: Here is my code in python, well commented; and with very good explanation for easy comprehension.... your code works well but is highly insecure and wasteful. reasons: 1. when proggie asks for input, enter "1 2" and "3" the second time. boom, index out of range!!! 2. when proggie asks for input, just hit enter. boom, proggie asks for input infinitely!!! 3. proggie allocates memory 3x for this simple algo: array, state_grid and rtn. boom, why oh why!!! |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by authurowen(m): 5:44am On Jun 24, 2013 |
WhiZTiM: my solution is uploaded on PasteBin... http://pastebin.com/r3cMG9sM
...Well there are [size=24pt]3 ways I know we could solve this[/size].
1. Procedural/functional ...like my implementation 2. Object Oriented 3. Mathematically.
1 You may have to be interested in Python to understand my code...(70lines uncommented, 122 lines commented) I was contemplating doing it in C++ or C# but thought it would be better in a lazy/weak typed language. **Ohkayy, I wouldnt talk on this cause all I would have said is represented VERY well in my Code
2 OOP: this would be similar to number 1... but in this case, all items can be treated as objects by wrapping them in light weighted classes.. ---These objects should be aware of their relative positions in the coordinate ---These objects should contain a boolean property that signifies whether its been used or not ---An abstract object or pointer can be used to transverse through the instantiated objects.. ---there should exist a simple (up, down, left, right) traveller function that will persistently travel in one direction until it reaches a limit or an object that has been taken... in this case, it changes direction in a preferential manner... ---this continues in spiral direction until there is no more object to transverse ---THIS CAN ALSO be DONE RECURSIVELY ...easier
3 MATHEMATICALLY: ...while I took a paper and was manually transversing through square matrices of diferent sizes... I realized that there exist this property of perfect squares:... ::: a summation of odd number sequences starting from 1 to n is equal to n^2. PROOF: if n = 3 1 + 3 + 5 = 9 if n = 5... 1 + 3 + 5 + 7 + 9 = 25 if n = 6 1 + 3 + 5 + 7 + 9 + 11 = 36 you can test for other cases
...now, assume a 5x5 grid.. A B C D E F G H I J K L M N O P Q R S T U V W X Y
using n as 5, we have the following sequence... (1 + 3 + 5 + 7 + 9)... reversing it, we have (9, 7, 5, 3, 1)... the first L shape is of 9 elements... that is ... (A, B, C, D, E, J, O, T, Y)... the next L shape is of 7 elements... that is ... (X, W, V, U, P, K, F).... the next L shape is of 5 elements... that is ... (G, H, I, N, S) the next L shape is of 3 elements... that is ... (R, Q, L) and finally the last is (M)...
[size=16pt]now... are you thinking mathematically....??[/size] yeah.... so, I did leave this method as a challenge to someone to implement authurowen's problem with MATHEMATICAL algorithm or discrete NUMERICAL algorithm....
"~~~Many programmers are really good, what may differentiate them is complex and subtle mathematical knowledge and skills~~~" ---says A renowned ACM-ICPC judge in Int'l Collegiate of Programming Contest....( I wish I recall the name)
NB: I am not a mathematician but a maths hobbyist... Brother, the solution is not as complicated as you have made it out to be. There is no need for the Mathematical / logical Gibberish (for lack of better words) you've just written. The lay Programmers would find it very difficult to comprehend your theory (I didn't even bother to look at it my self - NO USE!!) Keep it simple, thats how you tell who an SE is. |
Re: Code Challenge [1]: Pseudo-code, C#, JAVA (apply Object Oriented Principles) by authurowen(m): 5:52am On Jun 24, 2013 |
kambo: ------------------------------------------------------------------- Here's my solution. NLquiz.java (Test class) matrixPrinter.java (abstract class) spiralMatrixPrinter.java (implementing class) (C) nairaland.com/kambo ------------------------------------------------------------------------------
matrixPrinter.java --------------------------- //
public abstract class matrixPrinter { protected final String[][] grid; int Dim;//Dimension private int acceptedType=-1; //0 for int, 1 for char protected boolean locked=false; public matrixPrinter(final int dim) throws Exception { if(dim<0)throw new IllegalArgumentException("wrong dimension " Dim=dim; grid = new String[dim][dim]; for(int u=0;u<Dim;u++) for(int z=0;z<Dim;z++) grid[u][z]="";//init to negs } public void set(final int x,final int y,final char c) { if(x<0||x>=Dim||y<0||y>=Dim||locked) return; if(acceptedType==0)return; else { if(acceptedType==-1)acceptedType=1; grid[x][y]=String.valueOf(c); } } public void set(final int x,int y,int val) { if(x<0||x>=Dim||y<0||y>=Dim||locked) return; else { if(acceptedType>0)return; if(val<10&&val>=0) grid[x][y]=String.valueOf("0"+val); else grid[x][y]=String.valueOf(val); if(acceptedType==-1)acceptedType=0; } } public boolean allSet() { boolean ans=true; Outer: for(int y=0; y<grid.length;y++) for(int m=0; m<grid[y].length;m++) { if(grid[y][m]=="" {ans=false; break Outer;} } return ans; } public boolean isEmpty(){ boolean ans=true; Outer: for(int y=0;y<grid.length;y++) for(int x=0;x<grid.length;x++) { if(!grid[y][x].trim().equals("") { ans=false; break Outer; } } return ans; }
public void print(final String s){ System.out.print(s); System.out.print(" " }
public abstract void printGrid(); public final void actualLayout() { if(isEmpty())return; else { System.out.println(); for(int x=0;x<Dim;x++) { System.out.println(); for(int y=0;y<Dim;y++) {print(grid[x][y]); } } System.out.println(); } } }
------------------------------------------------------ spiralMatrixPrinter.java ------------------------------------------------------ // nairaland.com/kambo
public class spiralMatrixPrinter extends matrixPrinter { public spiralMatrixPrinter(final int Dim) throws Exception { super(Dim); }
public void printGrid() { // if(isEmpty())return; else { printer(0,grid.length-1); } } private void printer(final int s,final int max) { printer(s,max,1); } private void printer(final int start,final int maxIndex,int level) { if(start<0||maxIndex<0||maxIndex>=grid.length) { System.out.println(" arguments fail test returning.. : " //this method should throw an exception.. whatever.. } else { locked=true; //prevent data corruption.. int x=start; // x is a pointer for moving around the grid (the matrix) for(;x<=maxIndex;x++) print(grid[start][x]); // print top horizontal row //print vertical leftmost column x=start; x++; for(;x<=maxIndex;x++) print(grid[x][maxIndex]); //print bottom last row backwards. x=maxIndex; x--; for(;x>=start;x--) { print(grid[maxIndex][x]); } x=maxIndex; x--; //print rightMost column. for(;x>start;x--) { print(grid[x][start]); } System.out.print(" "
int start2=start; int maxI2=maxIndex; start2++; maxI2--; if(start2==maxI2) { //unlock access to data setting locked=false; //End case - the grid is an odd number length matrix. // print last cell. inner most cell print(grid[start2][maxI2]); return; } if(start2>maxI2) { //unlock locked=false; //end case - the matrix was even number length . return; } else printer(start2,maxI2,++level); } } } ---------------------------------------------------------------------------------------- NLquiz.java ----------------------------------------------------------------------------------------
// nairaland.com/kambo
// nairaland.com/kambo class NLquiz2 { public static void main(String ...s) throws Exception { int dim=1110; spiralMatrixPrinter sp = new spiralMatrixPrinter(dim); for(int x=0;x<dim;x++) for(int y=0;y<dim;y++) { //generate random numbers and feed em into the matrix printer int r = (int)((y*3)+ Math.random()*(x*y)); sp.set(x,y,r); } sp.actualLayout(); //print the initial array structure System.out.println(); sp.printGrid(); //print the spiral s tructure. } }------------------------------------------------------------------------------------------
NB: ----- Used an array of strings instead of integers for the sake of flexibility. the user could enter create two types of arrays , char arrays or integer arrays.
- expect an "out of memory " type exception to be thrown for large arrays. - initializing the class constructor to take an array could be done but i dont matter - really. i went the longhand way of passing variables individually to the matrix cells.
- I assume the array is balanced. not jagged and that all cells are filled with data.
------- Good try. I took a quick glance at your code, didn't test it out but It can BETTER be refactored and Improved. = No Need for the Abstract Class = - I assume the array is balanced. not jagged and that all cells are filled with data. This should not be a problem either as we wouldn't care a hoot what the array cells contain, but rather give more pressing concerns to the position of the Array index we are at to prevent getting an out of bound exception. = There are a lot of unnecessaries in your code as well. |