I just thought of this problem 15 minutes ago and even though it appears insanely easy I'm having a serious problem coming up with an answer.
Basically what I would like to do is based on a number (n) given by the user, I would like to draw a square shape.
Example: let's say the user gives the number 2, the result should be:
12
43
Now, suppose the user gives the number 3, the result should be:
123
894
765
etc..
Please don't give me the solution to this problem, I just want a clue or two to get me going.
I thought about doing it with a simple java class but I'm still struggling to get past the first condition:
public class DrawSquareWithNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your number: ");
int number = scanner.nextInt();
for (int i = 0; i <= number; i++) {
if (i<number)
System.out.print(i);
if (i>=number) {
System.out.println("\n"+i);
}
}
}
}
Any tip? Thanks in advance.
So I think I just put way too much time in this but it's a fun challenge so I thought let's give it a go.
I implented a code version for this solution and it works quite well although it's probably not the cleanest as I approached the whole problem backwards.
Here is my solution to try out online (note it's severely unoptimized and by no ways good Java code. It's a quick and dirty implementation to be honest):
https://ideone.com/97JB7Y
So the idea is quite simple: We first calculate the correct value for each position in a matrix and then we print that matrix out.
Let's go over it in a bit more detail:
We start of by creating the Matrix for our values to print:
With a given size n this is
int[][] values = new int[n][n];
Now we want to calculate the correct value at each point. I chose to tackle it the "wrong way" around by not starting at the first point but at the center of the spiral.
Basically imagine this matrix with n = 3:
[1][2][3]
[8][9][4]
[7][6][5]
Instead of at 1 I just start at 9. Reasoning for this is that it's actually easier to calculate the position spiraling out from a point over spiraling in to a point.
So starting at this center point we spiral out from there in a circular fashion. For the matrix
[1][2]
[4][3]
this means we visit 4 -> 3 -> 2 -> 1. And then just save the correct value in the matrix.
Only problem with my approach is that for a matrix with uneven size (3, 5, 7, etc.) I still visit the points in spiraling order, for 3x3 the order of visiting is e.g. 9 -> 4 -> 3 -> 2 -> 1 -> 8 -> 7 -> 6 -> 5, as visualized in this perfect picture I totally drew in Paint:
This leads to the result matrix being inversed as such:
[5][6][7]
[4][9][8]
[3][2][1]
This small problem is easily fixed though by simply printing the matrix out inversed once more should n%2 != 0.
Hope I could help with maybe a different approach to the problem.
I think you want to make nxn matrix with user entered number. So you can check the input and then you can use loop as for(i=1; i<=n; i++) for rows and similarly for column(for j=0;j<=n;j++) and then you can print your desired shape. Since you have asked to give you idea only so I am not posting any code here. If in case you get stuck somewhere you can refer : https://www.google.com/amp/s/www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/amp/
Ok, let's give this a try. First let's assume you'll have to store the matrix before printing it and that there's no magic formula that allows you to print what you need in a single iteration.
Now, you've the NxN matrix, for example for 3 it'd be 3x3, 9 positions. Instead of solving it with a series of ifs in an ugly way, you could use direction vectors for a cleaner solution. Also assume for now that you've another NxN matrix filled with booleans, all set to false, that will represent the already printed positions in the NxN matrix that you will print in the end. When you write a number in the final NxN matrix, you put the same position's boolean to true in the boolean matrix.
So for example, you want to print the positions of the first row, 1 2 3. You are displacing to the right to print. This'd be the direction (1,0), aka the starting direction vector. You advance through the NxN matrix using this coordinates. When you go outside the matrix (in the example, your x position is 3) you decrease your x position by one and you "spin" your direction vector (this should be done in a separate function). (1,0) would spin to (0,-1). You keep using this vector to iterate your matrix, spinning as necesary. After the first whole circle, you will get to an already printed position before going outside the matrix. So after every print you've to check not only if you go outside the matrix, but also if that position has already a number on it. For this, you use the boolean matrix.
This is how I'd solve it, there are probably many other ways (and better ones). For starters you could use null, or a mark, in the final matrix and save yourself the booleans one.
Create the result matrix beforehand, and declare a variable for the current number, starting value = 1, the current co-ordinates, starting with (0,0), the stepping direction starting with "to the right"
Start loop
Calculate the co-ordinates of next step, and check it
If it is off the matrix, then change direction, and re calculate, re-check
If free, then put the number in the matrix, increment it, and loop
If it is not free, then end loop, print out result matrix
Related
I'm new in programming and I'd like some help for an assignment, I only need a little clue to help me getting started (no answer, I only want to get a direction of how to do it then work my way).
The rules of the game : on the initial square is a marker that can move to other squares along the row. At each step in the game, you may move the marker the number of squares indicated by the integer in the square it currently occupies. The marker may move either left or right along the row but may not move past either end.
The goal of the game is to move the marker to the cave, the “0” at the far end of the row. In this configuration, you can solve the game by making the following set of moves:
eg: 2 3 1 2 4 0
first: move of 2 (to the right since it's impossible to go to the left) then: either move 1 to the right or 1 to the left then: if we moved left before: move 3 to the right (cannot go 3 to the left) if we moved right before then it's either 2 to the left or 2 to the right. 2 to the right is the right answer since then the next value is 0.
I must write the program that will try all the possibilities (so using a loop or a recursive I guess?) and return TRUE if there's a solution or FALSE if there are no solution. I had to choose the data structure from a few given by the prof for this assignment and decided to use an Array Based List since the get() is O(1) and it's mainly the only method used once the arraylist is created.
My program is only missing the (static?) method that will evaluate if it's possible or not, I dont need help for the rest of the assignment.
Assume that the ArrayBasedList is already given.
Thanks for your help!
I think your idea about using a recursive method makes a lot of sense. I appreciate you don't want the full answer, so this should just give you an idea:
Make a method (that passes in an integer x of the current position and your list) that returns a boolean.
In the method, check the value of list.get(x).
If it's 0, return true.
If it's -1, return false (more on that later).
Otherwise, store the value in a variable n, replace it with a -1, and return method(x+n) || method(x-n).
What the -1 does is it eventually fills everything in the array with a value that will terminate the program. Otherwise, you could end up with an infinite loop (like if you passed in [1, 2, 4, 2, 3]) with the value going back and forth.
A couple of things to keep in mind:
You'd need to make a new copy of the array every time, so you don't keep overwriting the original array.
You'd need to incorporate a try-catch (or equivalent logic) to make sure you are not trying to measure out of bounds.
If you have any further questions, feel free to ask!
Just thinking about the one algorithm below is the statement for that
Given a matrix, with each node having a value. You start from 0,0 and have to reach n,m. From i,j you can either go to i+1,j or i,j+1. When you step on each block, the value on that block gets added to your current score. What’s the minimum initial score you must carry so that you can always reach n,m(through any possible path) having positive score at the end.
Eg:
Matrix -> 2 3 4
-5 -6 7
8 3 1
Ans -> 6 – for path 2,-5,-6,3,1 we need initial score of 6 so that when we land on 1, we have a positive score of 1
So I can do this using brute force and Dynamic programming, but still thinking for approach which could be better then this, please share ur thoughts, just thoughts/idea I do not need implementation, as I can do this.
There's many search algorithm, i encourage you reading these Wikipedia pages :
https://en.wikipedia.org/wiki/Pathfinding
https://en.wikipedia.org/wiki/Tree_traversal
One possible solution, is to transform the array to graph and apply shortest paths algorithms to it, another solution is to use some IA algorithms such as A*.
Link to Wikipedia for A* (prounced A Star) :
https://en.wikipedia.org/wiki/A*_search_algorithm
I'm trying to solve the above problem using Java. Thought about using for loops but I can't see how this would work without knowing X and N in advance. I'm trying to solve it with recursion but not sure how it looks. Been trying for a couple hours now. Any help is greatly appreciated.
Example, if N = 4 and x = 3, possible arrays are:
[0,0,0,1]
[2,1,0,0]
[1,2,1,1]
[0,2,2,2]
My algorithem works like counting, you start counting until X (basiclly like counting in Base X) and when you get to X you add 1 to the next position in the Array and reset the last position.
so, as far as i know you can't return few arrays in a normal way so i'll assume you want to print them.
now, this is a "nice" code:
http://pastebin.com/Uqv3fMxg
few notes:
you should not make the function static, i did it from laziness.
this is not perfect, it print twice [1,0], [2,0] and so on. couln't find the problem and it is way too late for me, i'll try to check it again tommorow.
i'm not a guy that comments his code, i did a little but i'll explain everything i can here.
The program starts in the main method where i defined the Array and started the recurtion method.
The stop statement is when i got into the N position (that doesn't exist in the array, only N-1)
The parameters: the array, the position in the array that i am corrently counting and a "mode", is it a run to go to the next position or just to print all of the number in this position.
The alreadyHas variable is ment to not print number 2 times.
if i won't use it, it would print every number atleast 2 times, it will redo any work he has done until he move to this position and every position.
it is hard to explain, you can write 0 instead of it and see what happens.
so, i count until X, every time i print the new Array and to count every number and not skiping any i have to recount the last position with a different number in the last position.
after i have count all of the possible numbers in this possition, i am giving it a value of 0 and going to the next position.
so,to sum it up, you count the number in the first position of the array, when you reach the maximum you add a carry in the next position and reset the corrent position.
I've been stuck on this thing for a while, I just can't wrap my head around it. For a homework, I have to produce an algorithm for a sudoku solver that can check what number goes in a blank square in a row, in a column and in a block. It's a regular 9x9 sudoku and I'm assuming that the grid is already printed so I have to produce the part where it solves it.
I've read a ton of stuff on the subject I just get stuck expressing it.
I want the solver to do the following:
If the value is smaller than 9, increase it by 1
If the value is 9, set it to zero and go back 1
If the value is invalid, increase by 1
I've already read about backtracking and such but I'm in the early stage of the class so I'd like to keep it as simple as possible.
I'm more capable of writing in pseudo code but not so much with the algorithm itself and it's the algorithm that is needed for this exercise.
Thanks in advance for your help guys.
Seeing as it's homework, I believe I can point you in the general direction.
To start, keep a two-dimensional array (or a data structure that can represent the grid), and keep track of the values that can go there. Let's say it's a class named "possibilities":
public class Possibilities {
//Keep track of the numbers possible internally, with an accessor
}
The way sudoku works, there will usually be a square with only a single answer (in some cases, this won't be available, which means you need to potentially make a copy of the data and play out a little bit, or have a way to roll back). Simply put, fill in the answer, and then iterate over the adjacent squares to remove the freshly put number as a possibility (And check those squares simultaneously as new potential answers).
I think the easiest algorithm for solving a sudoku puzzle is a complete search. That is, trying every single combination until you find one that works. The easiest way to implement this is recursively. I know you don't want to get involved in backtracking, but I actually think that would be the easiest way for you to write this algorithm.
Assume you already have an algorithm that checks whether n can go in some cell at (i, j) in your board. This means that n does not violate any of the constraints (there can only be one number from 1 .. 9 in each row, column and box). This should not be too hard, you just have to loop through the row, column and box that contains cell (i, j) and make sure that n does not appear yet.
Then, you will have a recursive function called solve() that will return true if it finds a solution, otherwise it will return false. The function will constantly place numbers in empty cells of the sudoku board (only if they don't violate the constraints, which we assume you already write an algorithm for) until it is filled. Once filled, the puzzle is solved. You know that the board is valid because you've been checking the validity of every number you place on the way there. If no number can be placed at any point, it will backtrack by returning false.
The pseudocode for solve will look something like this:
boolean solve()
if the board is filled
return true
for each cell that is not empty
for n = 1 .. 9
if n does not exist in this row, column and box
place n in this cell
if solve()
return true
remove n from this cell
return false
I'm working on a program where I need to traverse a square from greatest distance to shortest distance, when starting from the center and given a maximum range that the object can travel.
The traversal would look something like this, each step is labeled starting from 0 to 35 (sorry for crappy diagram). Max distance would be 3 from center:
I was thinking it could work in two for loops, but I don't think that will work anymore without a ton of if statements. I want it to be semi-efficient if possible.
I don't need any code, just some ideas on how to get it to work (although feel free to post whatever).
Thanks for your help guys.
The simplest approach I can think of would involve 5 loops - one for each direction (all separate loops), and then one for the distance from the outside (which would be the outer-most loop).
The outer-most loop's value would allow us to determine where each loop should start and end.
As a rough draft, I imagine it would look something like this:
for i = 0 to n
for x = i to (n-i-1)
// process matrix[x][i]
for y = i to (n-i-1)
// process matrix[n-i][y]
for x = (n-i) downto i
// process matrix[x][n-i]
for y = (n-i) downto i
// process matrix[i][y]
I'll leave it to you to write the actual code.