Descending Order for SortCursor Class - java

So I've been using this great resource class i found online to Sort two cursors based on an column:
https://android.googlesource.com/platform/frameworks/base.git/+/android-4.4.4_r1/core/java/com/android/internal/database/SortCursor.java
The onMove function of this Cursor seems to be doing the sorting between the two cursors:
#Override
public boolean onMove(int oldPosition, int newPosition)
{
if (oldPosition == newPosition)
return true;
/*
* Find the right cursor
* Because the client of this cursor (the listadapter/view) tends
* to jump around in the cursor somewhat, a simple cache strategy
* is used to avoid having to search all cursors from the start.
* TODO: investigate strategies for optimizing random access and
* reverse-order access.
*/
int cache_entry = newPosition % ROWCACHESIZE;
if (mRowNumCache[cache_entry] == newPosition) {
int which = mCursorCache[cache_entry];
mCursor = mCursors[which];
if (mCursor == null) {
Log.w(TAG, "onMove: cache results in a null cursor.");
return false;
}
mCursor.moveToPosition(mCurRowNumCache[cache_entry][which]);
mLastCacheHit = cache_entry;
return true;
}
mCursor = null;
int length = mCursors.length;
if (mLastCacheHit >= 0) {
for (int i = 0; i < length; i++) {
if (mCursors[i] == null)
continue;
mCursors[i].moveToPosition(mCurRowNumCache[mLastCacheHit][i]);
}
}
if (newPosition < oldPosition || oldPosition == -1) {
for (int i = 0; i < length; i++) {
if (mCursors[i] == null)
continue;
mCursors[i].moveToFirst();
}
oldPosition = 0;
}
if (oldPosition < 0) {
oldPosition = 0;
}
// search forward to the new position
int smallestIdx = -1;
for (int i = oldPosition; i <= newPosition; i++) {
String smallest = "";
smallestIdx = -1;
for (int j = 0; j < length; j++) {
if (mCursors[j] == null || mCursors[j].isAfterLast()) {
continue;
}
String current = mCursors[j].getString(mSortColumns[j]);
if (smallestIdx < 0 || current.compareToIgnoreCase(smallest) < 0) {
smallest = current;
smallestIdx = j;
}
}
if (i == newPosition)
break;
if (mCursors[smallestIdx] != null) {
mCursors[smallestIdx].moveToNext();
}
}
mCursor = mCursors[smallestIdx];
mRowNumCache[cache_entry] = newPosition;
mCursorCache[cache_entry] = smallestIdx;
for (int i = 0; i < length; i++) {
if (mCursors[i] != null) {
mCurRowNumCache[cache_entry][i] = mCursors[i].getPosition();
}
}
mLastCacheHit = -1;
return true;
}
I'm not familiar with how cursors work but I was wondering how I would modify the onMove function such that the sorting of the two cursors would be sorted in desceding order rather than the default ascending order?
Any ideas would help! Thanks!

Related

Making a java 2048 game, upon sliding it goes through the loop more times than it should and hits tests/alters numbers already altered

So I have a solid slide function, the problem is (which is very hard to explain!) it goes through all the possibilities including spaces in the 2d array that have already been added together: say there is a setup like this: 4,4,8,2 ---after one swipe to the right, it ends up like this: ,_,16,2. however in the actual game, after one swipe right, it should look like this: ___,8,2.
Basically, how can I fix this? You don't need to tell me the code, it's my project for my final, but I'd like to get some sort of explanation as to why this is happening.
I've attempted to loop through the array from right to left but that resulted in the numbers not even moving.
processUserChoice(String i) {
if (i.equals("d")) {
while ((slideRight())) {
moveRight();
}
}
printBoard();
}
public boolean slideRight() {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length - 1; j++) {
if (board[i][j + 1] == 0 && board[i][j] != 0) {
return true;
} else if (board[i][j + 1] == board[i][j] && board[i][j] != 0) {
return true;
}
}
}
return false;
}
public void moveRight() {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length - 1; j++) {
if (board[i][j + 1] == 0 && board[i][j] != 0) {
board[i][j + 1] = board[i][j];
board[i][j] = 0;
} else if (board[i][j + 1] == board[i][j] && board[i][j] != 0) {
board[i][j + 1] = board[i][j + 1] + board[i][j];
board[i][j] = 0;
}
}
}
//checkLose();
}
After one swipe right, it should look like this:" ___,8,2 "(From the example before).
I did something similar to this in the past. I would to do it pretty much the same way as you are at the moment but add a Boolean array that checks if the tile has collided or not and only merges tiles that haven't been collided.
class Tile {
public int value;
public Boolean collided;
public Tile(int value) {
this.value = value;
collided = false;
}
public Tile attemptMerge(Tile target) {
if (target.value == value) {
Tile t = new Tile(value * 2);
t.collided = true;
return t;
} else {
return null;
}
}
public void reset() {
value = 0;
collided = false;
}
}
Somewhere in your main update loop:
void slideRight() {
for (int row = 0; row < 4; row++) {
for (int column = 3; column >= 0; column--) {
Tile current = board[row][column];
if (current.value == 0) continue;
for (int slot = column + 1; slot < 3; slot++) {
Tile target = board[row][slot];
if (target.value == 0) {
target.value = current.value;
current = target;
board[row][slot - 1].reset();
} else if (target.value == current.value) {
Tile product = target.merge(current);
if (!target.collided && !current.collided) {
current = product;
board[row][slot - 1].reset();
} else {
break;
}
} else {
break;
}
}
}
}
}
I believe something along those lines should work. Sorry if the logic is a bit flawed.

Exception being thrown for connect 4 algorithm

So I keep running into a problem with my code for checking if there is a connect 4 vertically. Preface to my code: the board has 6 rows and 7 columns, the variable player1 holds the value of the character being used as a chip and playerID just holds the value of whoever gets the connect 4.
public int verticalWin() {
int playerID = 0;
for (int x = 0; x < board[x].length; x++) {
int count = 1;
for (int y = board.length-2; y >= 0; y--) {
if (board[y][x] == board[y+1][x]) {
count++;
if (count == 4) {
if (board[y][x] == player1) {
playerID = 1;
} else {
playerID = 2;
}
}
} else {
count = 1;
}
}
}
return playerID;
}
The problem I keep running into is that an exception java.lang.ArrayIndexOutOfBoundsException: 6 keeps happening and I think it's in the first line, but I can't seem to find the problem.
Some cleaner code
boolean isWinnerOnColumn(int playerID, int column) {
int count = 0;
for (int row = 0; row < 6; row++) {
count = (board[row][column] == playerID) ? (count + 1) : 0;
if (count == 4){
return true;
}
}
return false;
}
public int verticalWin() {
for (int column = 0; column < 7; column++) {
if (isWinnerOnColumn(1, column) {
return 1;
}
if (isWinnerOnColumn(2, column) {
return 2;
}
}
return 0; // no winner
}

How to properly checkDiagonalWin in connect 4

My check vertical win and check horizontal win work perfectly fine, however i dont know what to do with my check diagonal code to make it actually check diagonal. Some guidance would be much appreciated and this is in java. Thank you.
private boolean checkVerticalWin()
{
PieceType type = myBoard[myLastPoint.x][myLastPoint.y];
System.out.println("check vert");
for(int j = 0; j < myNumColumns; j++)
{
for(int i = 0; i < myNumRows; i++)
{
if(myBoard[i][j] == type && myBoard[i][j] != null )
{
count++;
if(count == 1)
{
myWinBegin = new Point(i,j);
}
}
else
{
myWinBegin = null;
count = 0;
}
System.out.println(count);
if(count == myWinLength)
{
myWinEnd = new Point(i,j);
return true;
}
}
}
myWinBegin = null;
return false;
}
private boolean checkHorizontalWin()
{
System.out.println("test");
PieceType type = myBoard[myLastPoint.x][myLastPoint.y];
for(int i = 0; i < myNumRows; i++)
{
for(int j = 0; j < myNumColumns; j++)
{
if(myBoard[i][j] == type && myBoard[i][j] != null)
{
count++;
if (count == 1)
{
myWinBegin = new Point(i,j);
}
}
else
{
myWinBegin = null;
count = 0;
}
if(count == myWinLength)
{
myWinEnd = new Point(i,j);
return true;
}
}
}
myWinBegin = null;
return false;
}
private boolean checkDiagonalWin()
{
PieceType type = myBoard[myLastPoint.x][myLastPoint.y];
for(int i = 0; i < myNumRows; i++)
{
for (int j = 0; j < myNumColumns; j++)
{
if(myBoard[i][j] == type && myBoard[i][j] != null )
{
count++;
myWinBegin = new Point(i,j);
}
else
{
count = 0;
myWinEnd = new Point(i,j);
}
if(count == myWinLength)
{
return true;
}
}
}
for(int j = 0; j < myNumColumns; j--)
{
for (int i = 0; i < myNumRows; i--)
{
if(myBoard[i][j] == type && myBoard[i][j] != null )
{
count++;
myWinBegin = new Point(i,j);
}
else
{
count = 0;
}
if(count == myWinLength)
{
myWinEnd = new Point(i,j);
return true;
}
}
}
for(int j = 0; j < myNumColumns; j++)
{
for (int i = 0; i < myNumRows; i--)
{
if(myBoard[i][j] == type && myBoard[i][j] != null )
{
count++;
}
else
{
myWinBegin = new Point(i,j);
count = 0;
}
if(count == myWinLength)
{
myWinEnd = new Point(i,j);
return true;
}
}
}
for(int j = 0; j < myNumColumns; j--)
{
for (int i = 0; i < myNumRows; i++)
{
if(myBoard[i][j] == type && myBoard[i][j] != null )
{
count++;
myWinBegin = new Point(i,j);
}
else
{
count = 0;
}
if(count == myWinLength)
{
myWinEnd = new Point(i,j);
return true;
}
}
}
return false;
}
So basically, you need a start point, you then need to determine in which direction to move
With that idea in hand, you could use something like...
boolean win = true;
for (int count = 0; count < 4; count++) {
if (row < myNumRows && row >= 0 && col < myNumColumns && col >= 0) {
int test = myBoard[row][col];
if (test != check) {
win = false;
break;
}
} else {
break;
}
row += rowDelta;
col += colDelta;
}
As the basic algorithm. All this does is checks each cell from a start point, to a total of 4 cells, the algorithm moves by the specified delta/direction and keeps checking while each cell matches the check value.
Now, I'd wrap this in a simple method
public boolean didWin(int[][] grid, int check, int row, int col, int rowDelta, int colDelta) {
boolean win = true;
for (int count = 0; count < 4; count++) {
if (row < ROWS && row >= 0 && col < COLUMNS && col >= 0) {
int test = grid[row][col];
if (test != check) {
win = false;
break;
} else {
break;
}
}
row += rowDelta;
col += colDelta;
}
return win;
}
which makes it simpler to call, know given any point, you can do something like...
int startRow = ...;
int startCol = ...;
int player = ...;
if (didWin(myBoard, player, startRow, startCol, 1, 0) || // Vertical, down
didWin(myBoard, 1, startRow, startCol, 0, 1) || // Right
didWin(myBoard, 1, startRow, startCol, 0, -1) || // Left
didWin(myBoard, 1, startRow, startCol, 1, 1) || // Right/down
didWin(myBoard, 1, startRow, startCol, -1, -1) || // Left/Up
didWin(myBoard, 1, startRow, startCol, 1, -1) || // Down/Left
didWin(myBoard, 1, startRow, startCol, -1, 1) // Up/Right
) {
// You be the winner
}
nb: I've left out check a vertical up direction, because it's unlikely that you could actually win this way
ps: I'd be even more lazy and would just have a didWin method, which did the above checks and returned true or false, but I'm lazy
So, the startRow and startCol would represent the anchor point around which you want to check and would, in this example, represent the last drop.
This example uses a int to represent the player/token, but you could use anything, all this does is compares the token you supply with the values in the array

Zigzag conversion

Question is : The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
I have written below code, appearantly it works fine, but I might miss some corner cases. Could you help me to find all the corner cases for this question on my answer?
public static String zigZagConversion(String s , int rowNum){
if (s == null){
throw new IllegalArgumentException();
}
if (rowNum == 1){
return s;
}
StringBuilder str = new StringBuilder();
int step = 2 * rowNum - 2 ;
for (int i = 0 ; i < rowNum ; i++){
if( i == 0 || i == rowNum -1){
for (int j = i ; j < s.length() ; j +=step){
str.append(s.charAt(j));
}
}
else{
int step2 = 2* (rowNum - i - 1);
int step3 = step - step2;
int k = i;
boolean flag = true;
while (k < s.length()){
str.append(s.charAt(k));
if(flag){
k += step2;
flag = false;
}
else{
k +=step3;
flag = false;
}
}
}
}
return str.toString();
}
It gives incorrect output for "PAYPALISHIRING", 4
P I N
A L S I G
Y A H R
P I
So the correct answer should be PINALSIGYAHRPI.
But your program gives PINALIGYAIHRNPI:
an "S" is missing, one extra "I" and one extra "N".
Your revised version is still incorrect, it gives PINALSIIGYAHNPI.
The problem is in the while loop in the middle.
You need to alternate the step counting,
setting the flag on and off.
Your mistake was to only set it off once, and never back on again.
str.append(s.charAt(k));
if (flag) {
k += step2;
flag = false;
} else {
k += step3;
flag = true;
}
With this correction, I believe your solution is correct. (I also added a minor improvement there, extracting the common str.append(s.charAt(k)); from the if-else branches.
My solution on leetcode forum:
https://leetcode.com/problems/zigzag-conversion/discuss/549451/Java-Solution-O(n)-with-algorithm
The mathematic algorithm for zigzag is:
originalDiff = numRows * 2 - 2;
If -> 'currRow' equals First or last lines
use the originalDiff (numRows * 2 - 2)
Else ->
For each new line:
upperDiff += 2,
lowerDiff -=2
Examples:
numRows =2 -> originalDiff = 2
PYAIHRN
APLSIIG
3 -> 4
P A H N
A P L S I I G
Y I R
numRows = 4 -> originalDiff = 6
P I N
A L S I G
Y A H R
P I
numRows = 5 -> originalDiff = 8
P H
A SI
Y I R
P L I G
A N
*/
My solution:
class Solution {
public String convert(String s, int numRows) {
if(numRows == 1) {
return s;
}
String newString = "";
int originalDiff = numRows * 2 - 2;
int diff = originalDiff;
int upperDiff = 0;
boolean isGoingDown = true;
int currIndex = 0;
int currRow = 0;
int startingIndex = 0;
for(int i = 0; i < s.length(); i++) {
System.out.println(currIndex);
newString += s.charAt(currIndex);
if(currRow == 0 || currRow == numRows - 1) {
currIndex += originalDiff;
} else {
if(isGoingDown) {
currIndex += diff;
isGoingDown = !isGoingDown;
} else {
currIndex += upperDiff;
isGoingDown = !isGoingDown;
}
}
if(currIndex >= s.length()) {
currRow++;
diff -= 2;
upperDiff += 2;
currIndex = currRow;
isGoingDown = true;
}
if(currRow == numRows) {
i = s.length();
}
}
return newString;
}
}
Zigzag conversion from leetcode in Javascript
Solution
const zigzag = (str, num) => {
if (num === 1) {
return str;
}
let check = true;
let result = [];
let i = 0;
while (i < str.length) {
result.push([]);
let j = 0;
while (j < num) {
if (check){
result[result.length-1].push(str[i]);
i++;
} else {
if (j == 0) {
result[result.length-1].push(null);
} else if (j === num-1) {
result[result.length-1].unshift(null);
} else {
result[result.length-1].unshift(str[i]);
i++;
}
}
j++;
}
check = !check;
}
let zigzag = [];
for (let k = 0; k < num; k++){
for(let l = 0; l < result.length; l++) {
zigzag.push(result[l][k]);
}
}
return zigzag.join("");
}
Example Input
zigzag("ABCD", 3)
Output
ABDC
Run
https://repl.it/#VinitKhandelwal/zigzag-conversion-javascript
Using HashMap
public String convert(String s, int numRows) {
if (numRows == 1){
return s;
}
StringBuilder result = new StringBuilder();
Map<Integer, StringBuilder> map = new HashMap<>();
for (int i = 0; i < numRows; i++) {
map.put(i,new StringBuilder());
}
int it = 0;
boolean flip = true;
for (int i = 0; i < s.length(); i++) {
if (flip) {
if(it<s.length()){
map.get(it).append(s.charAt(i));
it++;
}
} else {
map.get(it).append(s.charAt(i));
it--;
}
if (it + 1 == numRows || it == 0)
flip = !flip;
}
for (Map.Entry entry: map.entrySet()) {
result.append(entry.getValue());
}
return result.toString();
}
My Solution is traversing the string in the same way it is said in the problem, it is better to make string array of size numrows and the rest is storing the string character as it is in the logic,
you can keep the index and when that index is 0 i.e at the starting then we have to go till the end of the row and then except for first and last row, every array will have diagonal element.
So after traversing till the end then assign index = numrows - 2 and save in the respective array string and decrease and do the same till index >0 and then again traverse till the end row, do this and when we reach the end of the string then break from the loop.
and then concate all the string of string array in a new res string.
class Solution {
public String convert(String s, int n) {
if(n==1 || n>=s.length())
return s;
String[] a = new String[n]; //string array
int ind=0; // index for the string array
boolean flag=true;
int cnt=0; //to keep the counter till where we have traversed the string
while(true && flag)
{
if(ind==0)
{
for(int i=0;i<n;i++)
{
a[i] += s.charAt(cnt);
cnt++;
if(cnt==s.length())
{
flag=false;
break;
}
} // here it has reached the end so we assign here
ind = n-2;
}
else if(ind>0 && ind<n && flag)
{
a[ind] += s.charAt(cnt);
cnt++;
if(cnt==s.length())
{
flag=false;
break;
}
ind--; // to move diagonally up
}
}
String res = new String("");
for(int i=0;i<a.length;i++)
{
// System.out.println(a[i].substring(4));
res += a[i].substring(4);
}
return res;
}
}
Following is the simple solution.
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows <= 1:
return s
res = ""
p = numRows * 2 - 2
temp = p
for i in range(0,numRows):
index = i
flag = 0
while index < len(s):
res = res + s[index]
if i == 0 or i == numRows-1:
index = index + p
else:
if flag == 0:
index = index + temp
flag = 1
else:
index = index + p-temp
flag = 0
temp = temp - 2
return res
zigzag-conversion Complete JavaScript-based solution
Created an Array of an array of row lengths. The main motive is to arrange characters in 2D array form and concat string row-wise.
var convert = function(s, numRows) {
let array =[],c=0,str='';
for(let row =0; row<numRows ; row++) {
array[row] = new Array();
}
while(c < s.length) {
for(let row =0; row<numRows ; row++) {
if((row+1)%numRows ==0) {
array[row].push(s[c]);
c++;
break;
} else {
array[row].push(s[c]);
c++;
}
}
for(let rr = numRows-2 ; rr>0;rr--) {
array[rr].push(s[c]);
c++;
}
}
for(let row =0; row<numRows ; row++) {
for(let i=0;i<array[row].length;i++){
if(array[row][i]){
str+=array[row][i]
}
}
}
return str
};
convert("PAYPALISHIRING",3)

selling a ticket and replacing the sold seat with a 0

This is a movie ticket theatre seller program. The task is create a method that takes the price of the user's input, finds the first seat and replaces it with a 0, denoting a sold seat. I keep fiddling with it but it keeps wanting to change all instances of the price input to 0 instead of the first found.
public boolean getByPrice(int price) {
boolean retVal = false; //initially false, have not found
System.out.println("You chose to buy a ticket with price: $" + price);
if (price == 10) {
for (int i = 0;i<NUM_ROWS;i++) {
for (int j = 0; j<NUM_COLS; j++) {
if (seats[i][j] == 10) {
retVal = true;
seats[i][j] = 0;
}
pricesAvailable[0] = pricesAvailable[0] - 1;
}
}
}
if (price == 20) {
for (int i = 0; i<NUM_ROWS;i++) {
for (int j = 0; j<NUM_COLS;j++) {
if (seats[i][j] == 20) {
retVal = true;
seats[i][j] = 0;
}
pricesAvailable[1] = pricesAvailable[1] - 1;
}
}
}
if (price == 30) {
for (int i = 0; i<NUM_ROWS;i++) {
for (int j = 0; j<NUM_COLS; j++) {
if (seats[i][j] == 30) {
retVal = true;
seats[i][j] = 0;
}
pricesAvailable[2] = pricesAvailable[2] - 1;
}
}
}
if (price == 40) {
for (int i = 0; i<NUM_ROWS;i++) {
for (int j = 0; j<NUM_COLS;j++) {
if (seats[i][j] == 20) {
retVal = true;
seats[i][j] = 0;
}
pricesAvailable[3] = pricesAvailable[3] - 1;
}
}
}
if (price == 50) {
for (int i = 0; i<NUM_ROWS;i++) {
for (int j = 0; j<NUM_COLS;j++) {
if (seats[i][j] == 50) {
retVal = true;
price = 0;
}
pricesAvailable[4] = pricesAvailable[4] - 1;
}
}
}
return retVal;
}
Also, the other part is to implement the same type of method using location
public boolean getByLoc(int row, int col) {
boolean retVal = false; //initially false
System.out.println("You chose row: " + row + ", col: " + col);
//************YOUR SOLUTION GOES HERE************//
for (int i = 0;i<NUM_ROWS;i++) {
for (int j = 0; j<NUM_COLS; j++) {
}
}
return retVal; //return value
}
I am not sure how use to make the location method work at all
Your loop does not exit when you found a seat. You could use break like:
for (int i = 0; i<NUM_ROWS && !retVal; i++){
for (int j = 0; j<NUM_COLS && !retVal; j++){
if (seats[i][j] == 10){
retVal = true;
seats[i][j] = 0;
break;
}
}
if (retVal) break;
}
or you could add a condition to your loops like:
for (int i = 0; i<NUM_ROWS && !retVal; i++){
for (int j = 0; j<NUM_COLS && !retVal; j++){
...
}
}
I would also recomend to reduce the code duplication by having the same loop in multiple ifs. How about summarizing it like this? (I assumed the pricesAvailable should only be lowerd when a seat has been found)
if (price == 0) { throw new IllegalArgumentException("Not giving away freebies"); }
for (int i = 0; i<NUM_ROWS && !retVal; i++){
for (int j = 0; j<NUM_COLS && !retVal; j++){
if (seats[i][j] == price){
retVal = true;
seats[i][j] = 0;
pricesAvailable[(price/10)-1]--;
}
}
}
Edit: Of couse returning inside the loops would also work if this is all you want to do in this method:
if (price == 0) { throw new IllegalArgumentException("Not giving away freebies"); }
for (int i = 0; i<NUM_ROWS; i++){
for (int j = 0; j<NUM_COLS; j++){
if (seats[i][j] == price){
seats[i][j] = 0;
pricesAvailable[(price/10)-1]--;
return true;
}
}
}
return false;
You'll probably want to utilise a break; somewhere if you intend to keep your code as it is.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
http://www.c4learn.com/java/java-break-statement/
You need to break the for-loop when you have found a matching seat, otherwise it will continue to check all the other seats.
You have two nested loops, but you want to break out of both. There are a few ways to do this, but as this is relatively simple code, a label will suffice. Take a look at http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html.
As the comments have pointed out, this is obviously homework, so I won't post a full code listing, instead, here is a snippet:
rows:
for (int i = 0; i < NUM_ROWS; i++)
{
cols:
for (int j = 0; j < NUM_COLS; j++)
{
if (seats[i][j] == 30)
{
retVal = true;
seats[i][j] = 0;
}
pricesAvailable[2] = pricesAvailable[2] - 1;
break rows;
}
}
Also, please use braces around if-statements, it's just another way to introduce bugs.
That is because you keep looping even after you have found the first seat with that price. The best thing here would be to use a method, like below, and return after you're done with the first one. This will solve both your refactoring problems and your incorrect values:
public boolean findFirst(int cost){
for (int i = 0;i<NUM_ROWS;i++)
for (int j = 0; j<NUM_COLS; j++)
if (seats[i][j] == cost){
seats[i][j] = 0;
pricesAvailable[cost / 10 - 1] -= 1;
return true;
}
return false;
}
Then call it from your getByPrice function like this:
public boolean getByPrice(int price) {
boolean retVal = false; //initially false, have not found
System.out.println("You chose to buy a ticket with price: $" + price);
if (price == 10)
retval = findFirst(10);
//rest of the code...
You should break the loop as soon as the place is found. Otherwise you'll put 0 on all places that have the price == 10.
if (price == 10) {
for (int i = 0;i<NUM_ROWS;i++) {
for (int j = 0; j<NUM_COLS; j++) {
if (seats[i][j] == 10) {
retVal = true;
seats[i][j] = 0; //and here break/return.
}
pricesAvailable[0] = pricesAvailable[0] - 1;
}
}
}
Also your basically copying the same code 5 times. What if there were 100 different prices? Whould you copy that code 100 times?
You should consider putting the code that is duplicated inside a method and the variable part (price in this example) should be an input parameter.
Moreover variable pricesAvailable is quite problematic. First it's not named the best way. Maybe seatsAvailableAtPrice would sound better? And I don't think that array is the best container for that - you should try using Map where first integer would be the price, and the second would be the number of seats left for that price.
Map<Integer, Integer> seatsAvailableAtPrice = new HashMap<Integer, Integer>();
Putting it all together you could create a method like that:
private void reserveFirstAvailableSeatForPrice(final int price) {
for (int i = 0;i<NUM_ROWS;i++) {
for (int j = 0; j<NUM_COLS; j++) {
if (seats[i][j] == price) {
seats[i][j] = 0;
seatsAvailableAtPrice.put(price, seatsAvailableAtPrice.get(price) - 1);
return;
}
}
}
}
As for the second part - isn't that just checking if i=row and j=col? And if so making a reservation (setting price to 0)?

Categories