How do I add to my int variables when I press a key? - variables

The title summed up what I am trying to figure out.
I am trying to get my int variables to increase and/or decrease depending on what directional key I press.
int x;
int y;
x = 0;
y = 0;
Console.WriteLine("X:" +x + "Y:" +y);
while (Console.Readkey().Key == ConsoleKey.UpArrow)
{
y = +1;
}
If I press the Up arrow nothing happens, if I press any other directional keys it will exit the Console. I fell that I am on the right track because of that alone.
Any help is awesome.

Here you go. I've written this in a way that I'm assuming does what you want it to do.
int x = 0;
int y = 0;
while (true)
{
Console.WriteLine("X:" + x + "Y:" + y);
ConsoleKey key = Console.ReadKey().Key;
Console.Clear();
if (key == ConsoleKey.UpArrow)
{
y += 1;
}
else if (key == ConsoleKey.DownArrow)
{
y -= 1;
}
else if (key == ConsoleKey.RightArrow)
{
x += 1;
}
else if (key == ConsoleKey.LeftArrow)
{
x -= 1;
}
}
It saves the current key in ConsoleKey key and then checks which direction was pressed, and modifies x or y as necessary.
Note that I also added a Console.Clear() so everything prints neatly instead of repeatedly one after another.

Brackets {} should appear after a while statement, and the k in "Readkey" should be capitalized (e.g. "ReadKey")
while (Console.ReadKey().Key == ConsoleKey.UpArrow)
{
y = +1;
}
Edit: There was as semi-colon after the while statement, making the loop null. This version should work.

Related

GlutKeyboardFunc callback doesn't work in openGL

I am trying to simply quit the application on pressing a key in openGL and the keyboard doesn't seem to work.
Neither am I am not able to quit the application just by clicking on the close button of the window. Any explanation for this behaviour? I am not recreating the window continuously either.
Here's the code snippet
void keyboardfunc(unsigned char key, int x, int y) {
cout << "Inside" ;
switch (key) {
case 'q': exit(0);
default: break;
}
int main(int argc,char ** argv)
{
.
.
.
glutReshapeFunc(reshape_func);
glutDisplayFunc(draw);
glutKeyboardFunc(keyboardfunc);
myinit();
glutMainLoop();
return 0;
}
The program is to simulate insertion sort by representing the array graphically , using a for loop I am clearing the screen every time and representing the numbers as histogram each time
Just to be clear the simulation of insertion sort works , only the keyboard callback doesn't work.
Your draw functions take the CPU control and don't let to execute GLUT events loop. Take into account that GLUT is single thread.
You must register a timer. Timer will produce new rendering. Each second compute next iteration and force to redraw scene.
void draw(){
renderHistogram();
}
void timer(int value) {
getNextIteration();
glutPostRedisplay();
glutTimerFunc(1000, timer, 1); // executed on a second
}
To register timer include this line before glutMainLoop:
glutTimerFunc(1000, timer, 1); // executed on a second
next iteration function would be:
int i = 0, j = 0;
void getNextIteration()
{
if (i == n) {
// Array is sorted
return;
}
int key;
key = arr[i];
if (j == 0 || arr[j] <= key) {
// Internal loop finished, reset j, and advance i;
arr[j + 1] = key;
i++;
j = i - 1;
}
arr[j + 1] = arr[j];
j = j - 1;
}

What is the time complexity of this function?

Here's a sample solution for Sliding Window Maximum problem in Java.
Given an array nums, there is a sliding window of size k which is
moving from the very left of the array to the very right. You can only
see the k numbers in the window. Each time the sliding window moves
right by one position.
I want to get the time and space complexity of this function. Here's what I think would be the answer:
Time: O((n-k)(k * logk)) == O(nklogk)
Space (auxiliary): O(n) for return int[] and O(k) for pq. Total of O(n).
Is this correct?
private static int[] maxSlidingWindow(int[] a, int k) {
if(a == null || a.length == 0) return new int[] {};
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k, new Comparator<Integer>() {
// max heap
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
int[] result = new int[a.length - k + 1];
int count = 0;
// time: n - k times
for (int i = 0; i < a.length - k + 1; i++) {
for (int j = i; j < i + k; j++) {
// time k*logk (the part I'm not sure about)
pq.offer(a[j]);
}
// logk
result[count] = pq.poll();
count = count + 1;
pq.clear();
}
return result;
}
You're right in most of the part except -
for (int j = i; j < i + k; j++) {
// time k*logk (the part I'm not sure about)
pq.offer(a[j]);
}
Here total number of executions is log1 + log2 + log3 + log4 + ... + logk. The summation of this series -
log1 + log2 + log3 + log4 + ... + logk = log(k!)
And second thought is, you can do it better than your linearithmic time solution using double-ended queue property which will be O(n). Here is my solution -
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums == null || k <= 0) {
return new int[0];
}
int n = nums.length;
int[] result = new int[n - k + 1];
int indx = 0;
Deque<Integer> q = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
// remove numbers out of range k
while (!q.isEmpty() && q.peek() < i - k + 1) {
q.poll();
}
// remove smaller numbers in k range as they are useless
while (!q.isEmpty() && nums[q.peekLast()] < nums[i]) {
q.pollLast();
}
q.offer(i);
if (i >= k - 1) {
result[indx++] = nums[q.peek()];
}
}
return result;
}
HTH.

Time/Space-Complexity method

I got a question to answer with the best complexity we can think about.
We got one sorted array (int) and X value. All we need to do is to find how many places in the array equals the X value.
This is my solution to this situation, as i don't know much about complexity.
All i know is that better methods are without for loops :X
class Question
{
public static int mount (int [] a, int x)
{
int first=0, last=a.length-1, count=0, pointer=0;
boolean found=false, finish=false;
if (x < a[0] || x > a[a.length-1])
return 0;
while (! found) **//Searching any place in the array that equals to x value;**
{
if ( a[(first+last)/2] > x)
last = (first+last)/2;
else if ( a[(first+last)/2] < x)
first = (first+last)/2;
else
{
pointer = (first+last)/2;
count = 1;
found = true; break;
}
if (Math.abs(last-first) == 1)
{
if (a[first] == x)
{
pointer = first;
count = 1;
found = true;
}
else if (a[last] == x)
{
pointer = last;
count = 1;
found = true;
}
else
return 0;
}
if (first == last)
{
if (a[first] == x)
{
pointer = first;
count = 1;
found = true;
}
else
return 0;
}
}
int backPointer=pointer, forwardPointer=pointer;
boolean stop1=false, stop2= false;
while (!finish) **//Counting the number of places the X value is near our pointer.**
{
if (backPointer-1 >= 0)
if (a[backPointer-1] == x)
{
count++;
backPointer--;
}
else
stop1 = true;
if (forwardPointer+1 <= a.length-1)
if (a[forwardPointer+1] == x)
{
count++;
forwardPointer++;
}
else
stop2 = true;
if (stop1 && stop2)
finish=true;
}
return count;
}
public static void main (String [] args)
{
int [] a = {-25,0,5,11,11,99};
System.out.println(mount(a, 11));
}
}
The print command count it right and prints "2".
I just want to know if anyone can think about better complexity for this method.
Moreover, how can i know what is the time/space-complexity of the method?
All i know about time/space-complexity is that for loop is O(n). I don't know how to calculate my method complexity.
Thank a lot!
Editing:
This is the second while loop after changing:
while (!stop1 || !stop2) //Counting the number of places the X value is near our pointer.
{
if (!stop1)
{
if ( a[last] == x )
{
stop1 = true;
count += (last-pointer);
}
else if ( a[(last+forwardPointer)/2] == x )
{
if (last-forwardPointer == 1)
{
stop1 = true;
count += (forwardPointer-pointer);
}
else
forwardPointer = (last + forwardPointer) / 2;
}
else
last = ((last + forwardPointer) / 2) - 1;
}
if (!stop2)
{
if (a[first] == x)
{
stop2 = true;
count += (pointer - first);
}
else if ( a[(first+backPointer)/2] == x )
{
if (backPointer - first == 1)
{
stop2 = true;
count += (pointer-backPointer);
}
else
backPointer = (first + backPointer) / 2;
}
else
first = ((first + backPointer) / 2) + 1;
}
}
What do you think about the changing? I think it would change the time complexity to O(long(n)).
First let's examine your code:
The code could be heavily refactored and cleaned (which would also result in more efficient implementation, yet without improving time or space complexity), but the algorithm itself is pretty good.
What it does is use standard binary search to find an item with the required value, then scans to the back and to the front to find all other occurrences of the value.
In terms of time complexity, the algorithm is O(N). The worst case is when the entire array is the same value and you end up iterating all of it in the 2nd phase (the binary search will only take 1 iteration). Space complexity is O(1). The memory usage (space) is unaffected by growth in input size.
You could improve the worst case time complexity if you keep using binary search on the 2 sub-arrays (back & front) and increase the "match range" logarithmically this way. The time complexity will become O(log(N)). Space complexity will remain O(1) for the same reason as before.
However, the average complexity for a real-world scenario (where the array contains various values) would be very close and might even lean towards your own version.

Programming Chess Rook Movement

I am trying to create a board game where all the pieces are able to move the same as a rook in chess. (i.e. Horizontally or vertically as many spaces as they wish)
My board is a simple 2d integer array, with values of 0,1,2 depending on whether the space is empty, has a red piece or a black piece.
My code for the movement so far is shown below, it creates a true or false value if the move is allowed or not:
int[][] board;
public boolean validMove(int fromRow, int fromCol, int toRow, int toCol) {
if (pieceAt(toRow, toCol) != EMPTY) {
return false;
} else if (fromRow - toRow == 0 && fromCol - toCol != 0) {
return true;
} else if (fromCol - toCol == 0 && fromRow - toRow != 0) {
// Trying to add piece collision code
for (int i = fromRow; i < toRow; i++) {
if (pieceAt(toCol, i) != EMPTY)
return false;
}
return true;
} else {
return false;
}
}
My problem is trying to create collision detection, if another piece is in the way it should not be able to move past it, however with my code currently it can. Can anyone help me do this?
Try code below. It's quite naive (and also not tested), but I think it should work just as is. And also I think it illustrates the idea pretty well (see comments). It's in C, but I'm sure you can transform it easily to Java (or whatever language you use).
bool validMove(int fromRow, int fromCol, int toRow, int toCol)
{
int i;
// Attempt to move to the same cell
if (fromRow == toRow && fromCol == toCol)
return false;
// Collision detection
if (fromRow == toRow) {
// Horizontal move
if (fromCol < toCol) {
// Move right
for (i = fromCol + 1; i <= toCol; ++i)
if (pieceAt(fromRow, i) != EMPTY)
return false;
} else {
// Move left
for (i = fromCol - 1; i >= toCol; --i)
if (pieceAt(fromRow, i) != EMPTY)
return false;
}
} else if (fromCol == toCol) {
// Vertical move
if (fromRow < toRow) {
// Move down
for (i = fromRow + 1; i <= toRow; ++i)
if (pieceAt(i, fromCol) != EMPTY)
return false;
} else {
// Move up
for (i = fromRow - 1; i >= toRow; --i)
if (pieceAt(i, fromCol) != EMPTY)
return false;
}
} else {
// Not a valid rook move (neither horizontal nor vertical)
return false;
}
return true;
}
EDIT
You can also optimize your code by reducing conditional statement count, using the method proposed by Toon Krijthe. The main idea is to use "delta" values (dx/dy) for incrementing or decrementing cell indexes. In that case the destination cell should be checked explicitly.
Code:
bool validMove(int fromRow, int fromCol, int toRow, int toCol)
{
int i;
// Attempt to move to the same cell
if (fromRow == toRow && fromCol == toCol)
return false;
// Collision detection
if (fromRow == toRow) { // Horizontal move
int dx = (fromCol < toCol) ? 1 : -1;
for (i = fromCol + dx; i != toCol; i += dx)
if (pieceAt(fromRow, i) != EMPTY)
return false;
} else if (fromCol == toCol) { // Vertical move
int dy = (fromRow < toRow) ? 1 : -1;
for (i = fromRow + dy; i != toRow; i += dy)
if (pieceAt(i, fromCol) != EMPTY)
return false;
} else { // Not a valid rook move
return false;
}
// Return true if destination cell is free
return pieceAt(toRow, toCell) == EMPTY;
}
you could have a 2D char array with each cell representing the position on the board. there you can have a char for the three states of the position (white/red/empty).
The other way i can think of is before each move to check from the startPosition till the endPosition positions their states. but performance wise i think the some kind of array will be much better
You can simply "walk" each field in order to check if it is empty.
For example:
int[][] board;
public boolean validMove(int fromRow, int fromCol, int toRow, int toCol)
{
if (pieceAt(toRow, toCol) != EMPTY) return false;
else if (fromRow == toRow)
{
// horizontal move
if (fromCol == toCol) return false; // same position
int dx, x;
if (fromCol < toCol)
dx = 1;
else
dx = -1;
for (x = fromCol + dx; x != toCol; x += dx)
{
if (pieceAt(toRow, x) != EMPTY) return false; // occupied
}
}
else if (fromCol == toCol)
{
// vertical move
int dy, y;
if (fromRow < toRow)
dy = 1;
else
dy = -1;
for (y = fromRow + dy; y != toRow; y += dy)
{
if (pieceAt(y, toCol) != EMPTY) return false; // occupied
return true; // free path
}
}
else return false; // no horizontal or vertical move
}

determinant algorithm of a 4x4 matrix

I pick the first row and multiply each element by its cofactor,
but in some cases the method is returning nan.
For example,
1 0 0 1
0 2 0 0
0 0 3 0
0 0 0 4
in this case the method returns nan.
Does anyone know what I did wrong?
getDet3 returns determinant of a 3x3 matrix and it works fine.
-(double) getDet4:(double[4][4])mat {
double det = 0;
double small[3][3];
int i, j, k;
int i_ = 1, j_;
for ( i=0; i<4; i++ ){
if (mat[0][i] == 0) continue;
// get the small matrix here
for ( j=0; j<3; j++ ){
j_ = 0;
for ( k=0; k<3; k++ ){
if ( i == j_ ) j_++;
small[j][k] = mat[i_][j_];
j_++;
}
i_++;
}
det += mat[0][i] * [self getDet3:small] * pow(-1, i+j);
}
return det;
}
Well, there are a few mistakes in your code.
1) The initialization of i_ = 1 should be done just before the j loop, otherwise it will keep the old value.
2) The computation of pow(-1, i+j) should only depend on i, since j has the same value every time in that expression (namely, 3).
So, assuming that getDet3 is correct, the mistake is introduced by i_ going out of bounds. As a whole, the code should look like:
-(double) getDet4:(double[4][4])mat {
double det = 0;
double small[3][3];
int i, j, k;
int i_, j_;
for ( i=0; i<4; i++ ){
if (mat[0][i] == 0) continue;
// get the small matrix here
i_ = 1;
for ( j=0; j<3; j++ ){
j_ = 0;
for ( k=0; k<3; k++ ){
if ( i == j_ ) j_++;
small[j][k] = mat[i_][j_];
j_++;
}
i_++;
}
det += mat[0][i] * [self getDet3:small] * pow(-1, i);
}
return det;
}
Personally, I find your variable names confusing. If I understand your idea correctly, you expect i_ to have the value j + 1 and j_ to be k < i ? k : k + 1. IMHO, it would have been less confusing to have named them j_p andk_`, or even to just use the equivalent expression.
In any event, you don't reinitialize i_ inside the outer for loop. So it actually just keeps on incrementing, resulting in array indices outside of the array bounds.