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
Related
how can i do that someone ?
i had problem about that
Enter the mode: A
Enter the minimal possible integer: 1
Enter the maximal possible integer: 10
I have generated a random integer between 1 and 10.
Try to guess: 5
No. It is smaller!
Try to guess: 3
Done.
Enter the mode: B
Enter the minimal possible integer: 1
Enter the maximal possible integer: 10
Generate a random integer between 1 and 10...
Which method I should use to guess it?
1: Binary search
2: Interpolation search
Enter your choice of the method: 1
Is it 5? (<, >, =)
<
Is it 3?
Done.
Learning different search algorithms is very interesting.
Since you say that you need to learn, I present you the theoretical explanation of both algorithms.
Binary search
This is a computer science search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half, again taking the middle element to compare to the target value, and repeating this until the target value is found. If the search ends with the remaining half being empty, the target is not in the array.
Interpolation search
Instead of calculating the midpoint, interpolation search estimates the position of the target value, taking into account the lowest and highest elements in the array as well as length of the array. This is only possible if the array elements are numbers. It works on the basis that the midpoint is not the best guess in many cases. For example, if the target value is close to the highest element in the array, it is likely to be located near the end of the array.
To find the position to be searched, it uses following formula.
pos = lo + [ (x-arr[lo])*(hi-lo) / (arr[hi]-arr[Lo]) ]
arr[] -> Array where elements need to be searched
x -> Element to be searched
lo -> Starting index in arr[]
hi -> Ending index in arr[]
Source Wikipedia Binary Search
How you wish to implement them is at your own discretion.
If you are stuck with that and post the code of your attempt, we can help you more.
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
I need help in solving this problem, I tried using a 2D array and then finding the least number of swaps. Not sure exactly how to go about this problem. Whether to use BFS or DFS?
You are given two four digits numbers. The first number is the initial number, and the second one is the target number. Write a java program to transform the initial number into the target number using the fewest possible operations. The available operations are as follows:
Add 1 to one of the four digits. Adding 1 to a 9 results in 0.
Subtract 1 from one of the four digits. Subtracting 1 from 0 results in 9.
Swap two adjacent digits
eg 1:
initial no :1111
final no : 9999
min no of operations :8
eg 2:
initial no :1234
final no : 2144
min no of operations :2
BFS.
When DFS finds first solution it is usually not one found in the smallest possible number of moves. It can also explore long, pointless paths when solution is close (it can get stuck in infinite loop if you don't remember visited nodes). These problems could be solved by iterative deepening DFS, which might be desirable if there are memory constraints, but BFS is simpler for such small search space.
You should use BFS algorithm, because it will give you the shortest possible way to transform the first number to the targeted one. DFS only explore the paths, and not by shortest way. In some cases, DFS might find the solutions faster than BFS, but there is no algorithmic guarantee for that.
I've never used DFS before and I was wondering how you could use one to find the smallest product of a path if you were to traverse through the following "tree":
3
4 5
7 6 4
3 5 7 8
1 2 3 4 4
See comments below to clear any confusion(:
You need to construct a directed graph, where the nodes are the numbers, and each node has 2 edges to a number/node on the next level. The graph in this particular problem will be a directed acyclic graph.
Then, you just run DFS on the graph constructed. However, you will not keep track of/check whether you have visited a node before or not, since you want to revisit them. Instead, you only need to check whether the current node has 0 out-degree or node (since the nodes at the bottom will have 0 out-degree), and update the current min when you reach the nodes at the bottom. (You may also keep track of the current depth, and update the current min when the depth is reached). We can do this for this particular problem, since all the products is the result of multiplying exactly 5 numbers, one from each level.
What I describe above is called tree search variant of DFS, compared to the normal graph-search variant where you keep track whether a node has been visited before. Tree search DFS will get stuck when there is a cycle in the graph, but since this is a directed acyclic graph, we will not run into such problem.
If the numbers are all non-negative, we can observe that: regardless of how we reach a node from the root, the optimal path ahead is going to be the same every time.
In such case, it is faster to work backward from the bottom nodes. For each pairs that are adjacent to the same "parent" node, pick the smaller one and multiply with the "parent" node. Keep doing so until you reach the root node, and you will get the result.
If the numbers can be positive or negative or 0, you need to keep track of 4 numbers: negative product with the largest and smallest absolute value, largest and smallest positive product. And you also need to keep track of whether 0 product can be formed or not. The 2 largest absolute value are for the case of positive x negative. The 2 smallest absolute value are for the case of positive x positive or negative x negative. At the start of the algorithm, all those 5 fields are undefined.
The details of how to update are left to the readers. The result should be checked in the order: the negative number with the largest absolute value, 0, the positive number with the smallest absolute value. If the field is undefined, then skip it and check the next one.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Can you answer this 2009 ACM International Collegiate Programming Contest Finals problem?
Hi,
I am attempting to do question 1 here-> http://cm.baylor.edu/ICPCWiki/attach/Problem%20Resources/2009WorldFinalProblemSet.pdf
and cannot really come up with a good algorithm to solve it :
Basically, there are n planes, n is read in from standard input. There are then n intervals for times in which the planes can arrive, you must compute the largest interval between all planes that is possible. So, say
n = 3
and you are given the inputs
0 10
5 15
10 15
The answer is : 7: 30, the largest possible interval between planes.
Not really sure how I would go about solving this. Any tips ?
For the first plane, select the earliest possible arrival time
For the last plane, select the latest possible arrival time
For elements 2 through element n-1:
Search for a midpoint plane by dividing the range between element 1 and element n
(Hopefully, that will be close to the element n/2)
recursivly call the same function for element 1 and the midpoint element
recursivly call the same function for the element after the midpoint element and element n
That will evenly divide up the time available within the constraints of the planes scheduled windows.
Once you have roughly evenly spaced windows, select the smallest window and test it with its neighboring planes to see if they can shift some to expand the smallest window. Repeat this process until the smallest window can't shift a significent amount.