It's my job to test exercises for other students. Today I got a really difficult one (at least for me) and I'm not sure if I'm just a blockhead right now.
I got a 2D char Array and 3 Strings which I have to find in there. The words can span horizontal, vertical, and diagonal; forwards or backwards. The problem: I'm not allowed to use any methods, everything has to be inside the main method.
I don't find a way which doesn't have like < 10 loops. Do you have a smart idea?
I mean, this is the obvious way, of courseā¦
Comparisons could be slightly sped up with Boyer-Moore or similar.
for row in haystack:
for character in row:
#check if pattern or reversed pattern matches
for column in haystack:
for character in column:
#check if pattern or reversed pattern matches
for positively-sloped-diagonal in haystack:
for character in diagonal:
#check
for negatively-sloped-diagonal in haystack:
for character in diagonal:
#check
Depending on the exact parameters, it could be a little bit less braindead to do something like:
for each pattern:
for each slot in the array:
for horizontal in [-1, 0, 1]:
for vertical in [-1, 0, 1]:
if horizontal == vertical == 0:
pass
for n in range(pattern.length):
if pattern[n] != haystack[row + n * vertical][column + n * horizontal]
break
#Pattern found
#Pattern not found
You can recursively call the main method to search forward, backward, up, down, left-up/down diagonal, and right-up/down diagonal.
if (arg[2] == array.length && arg[3] == array.length)
return 0;
if (firstTimeMainFunctionCalled) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
// Only make recursive call when you are
// on the outer edge of the 2D array
if (i == 0 || j == 0) {
main(1, 0, i, j);
main(0, 1, i, j);
main(1, 1, i, j);
main(-1, 0, i, j);
main(0, -1, i, j);
main(-1, -1, i, j);
main(1, -1, i, j);
main(-1, 1, i, j);
}
}
}
int rowInc = arg[0];
int colInc = arg[1];
int curRow = arg[2];
int curCol = arg[3];
int str1Place = 0;
int str2Place = 0;
int str3Place = 0;
while (curRow >= 0 && curCol >= 0 && curRow < array.length && curCol < array[0].length) {
if (array[curRow][curCol] == str1[str1Place])
str1Place++;
else
str1Place = 0;
if (str1Place == str1.length)
// Found str1
// Do the same for str2 and str3
curRow += rowInc;
curCol += colInc;
}
This is a very crude solution and can be improved a whole lot, you obviously have to call the main method appropriately by turning the arguments into a list of strings but it should give you somewhere to start. You can improve this using dynamic programming, you can also backtrack to do something with the string once you find it. Also, as you can see the nested loop doesn't need to be nested.
Pardon my pseudocode :)
Related
I'm trying to make a Java program to find the number of consecutive numbers in an array. For example, if an array has the values, 1,8,10,4,2,3 there are 4 numbers that are consecutive (1,2,3,4). I've created this program, but I'm getting an error on lines 28 and 31 for ArrayIndexOutOfBoundsException, how do I fix the error? (I'm not even sure if the program I made will work if the errors are fixed). Note: I know there are many solutions online for this but I'm a beginner programmer, and I'm trying to do this a more simple way.
import java.util.Arrays;
class Main {
public static void main(String[] args) {
consec();
}
static void consec()
{
int[] nums = {16, 4, 5, 200, 6, 7, 70, 8};
int counter=0;
Arrays.sort(nums);
for (int i=0; i < nums.length; i++)
if (i != nums.length - 1)
System.out.print(nums[i] + ", ");
else
System.out.print(nums[i]);
for (int i=0; i < nums.length; i++)
for (int j=i; j < nums.length - i; j++)
if (nums[j + 1] - 1 == nums[j])
counter++;
else if (nums[j+1]==counter)
System.out.print("Consective amount is" + counter);
}
}
The issue for the exception lies within the access of nums[j + 1].
Note that j can be as large as nums.length - 1 due to the for loop.
Thus j + 1 can be nums.length which is an OutOfBounds array index.
Secondly I don't think your code solves the task - for example you only print a result if the number of consecutive numbers you've counted appears within the array. However I don't see how these things should correlate.
You can solve the problem like this:
for (int i = 1; i < nums.length; i++) {
if (nums[i-1] == nums[i] - 1) {
counter+= 2;
int j = i + 1;
while (j < nums.length && nums[j] - 1 == nums[j-1]) {
j++;
counter++;
}
i = j;
}
}
System.out.print("Consective amount is" + counter);
Note that the index i starts at 1, thus we can be assured that nums[i-1] exists.
If nums has only one element we should not run into any issues as the condition i < nums.length would not be fulfilled. We count two consequitves for every start of a sequence and one addition element for every following consequtive (while loop).
When the sequence ends we try finding a new sequence behind it by moving the index i to the end of the last sequence (j = i).
The above code will sum multiple distinct sequences of consequtive numbers. For example the array [17,2,20,18,4,3] has five consequitve numbers (2,3,4 and 17,18)
The algorithm has a time colpexity within O(n) as we either increase i or j by at least on and skip i to j after each sequence.
I would recommend re-thinking your approach to scanning over the array. Ideally you should only require one for-loop for this problem.
I personally created a HashSet of Numbers, which cannot hold duplicates. From there, you can iterate from 1 to nums.length-1, and check if nums[i] - 1 == nums[i-1] (ie: if they're consecutive). If they are equal, you can add both numbers to the HashSet.
Finally, you actually have the set of consecutive numbers, but for this question, you can simply return the size of the set.
I strongly recommend you attempt this problem and follow my explanation. If you simply require the code, this is the method that I came up with.
public static int countConsecutive(int[] nums) {
Set<Integer> consecutive = new HashSet<>();
if (nums.length <= 1)
return 0;
Arrays.sort(nums);
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[i - 1] + 1)
continue;
consecutive.add(nums[i]);
consecutive.add(nums[i - 1]);
}
return consecutive.size();
}
Here is another approach where sorting is not necessary. It uses a BitSet. And as in your example, is presumes positive numbers (BitSet doesn't permit setting negative positions).
int[] values = {4, 3, 10, 11, 6, 1, 4, 8, 7};
set the corresponding bit positions based on the values.
BitSet bits = new BitSet();
for (int i : values) {
bits.set(i);
}
Initialize some values for output, starting bit position, and the set length.
BitSet out = new BitSet();
int start = 0;
int len = bits.length();
Now iterate over the bit set finding the range of bits which occupy adjacent positions. Those will represent the consecutive sequences generated when populating the original BitSet. Only sequences of two or more are displayed.
while (start < len) {
start = bits.nextSetBit(start);
int end = bits.nextClearBit(start+1);
if (start != end-1) {
// populate the subset for output.
out.set(start,end);
System.out.println(out);
}
out.clear();
start = end;
}
prints
{3, 4}
{6, 7, 8}
{10, 11}
If you just want the largest count, independent of the actual values, it's even simpler. Just use this in place of the above after initializing the bit set.
int len = bits.length();
int total = 0;
while (start < len) {
start = bits.nextSetBit(start);
int end = bits.nextClearBit(start + 1);
if (end - start > 1) {
total += end - start;
}
start = end;
}
System.out.println(total);
I trying to find all 2s, move them to the back of the array, and turn them into 0s without loosing the order of the array. For example, [1,2,3,2,2,4,5] would become [1,3,4,5,0,0,0]. My code works fine but the IDE is telling me that the nested for loop is copying the array manually and wants me to replace it with System.arraycopy(). How would I go about that?
Code looks like this:
int[] numbers = {1,2,3,2,2,4,5};
for (int i = 0; i < numbers.length; i++){
if (numbers[i] == 2){
for (int j = i; j < numbers.length - 1; j++){
numbers[j] = numbers[j + 1];
}
numbers[numbers.length-1] = 0;
i --;
}
}
The following statement:
for (int j = i; j < numbers.length - 1; j++){
numbers[j] = numbers[j + 1];
}
Can be replaced by:
System.arraycopy(numbers, i + 1, numbers, i, numbers.length - 1 - i);
IDEs like IntelliJ should suggest that automatically when you press alt + enter (default key combination).
Now about arraycopy()
From the documentation, java.lang.System.arraycopy() will copy n elements (last argument) from the source array (1st argument) to the destination array (3rd argument) with the corresponding indexes to start from (2nd and 4th arguments).
More specifically, when calling arraycopy(numbers, i + 1, numbers, i, numbers.length - 1 - i) the arguments are:
numbers: The source array.
i + 1: The starting position in the source array.
numbers: The destination array.
i: The starting position in the destination data.
numbers.length - 1 - i: The number of array elements to be copied.
In your case, elements will be copied from your array, to itself, but the fact that source starting position is shifted from the destination starting position will induce the global shifting you're after (moving elements to the left).
About the number of elements to be moved, it should move i elements minus the first one that doesn't move and only gets overwritten. Hence the length - 1 - i.
The inner loop could be replaced with an arraycopy, however, you don't need an inner loop:
int[] numbers = {1,2,3,2,2,4,5};
int j = 0;
for (int i = 0; i < numbers.length; i++){
if (numbers[i] != 2){
numbers[j++] = numbers[i];
}
}
while (j < numbers.length) {
numbers[j++] = 0;
}
UPDATE
Or even:
int[] numbers = {1,2,3,2,2,4,5};
int j = 0;
for (int n: numbers){
if (n != 2){
numbers[j++] = n;
}
}
Arrays.fill(numbers,j,numbers.length,0);
The key thing is pretty simple: if you can reduce the lines of code you are responsible for (for example by using utility methods such as Arrays.arraycopy()) - then do that.
Keep in mind: each line that you write today, you have to read and understand tomorrow, and to probably modify in 5 weeks or months from now.
But then: I think you are over-complicating things here. I would use a temporary list, like this:
List<Integer> notTwos = new ArrayList<>();
int numberOfTwos = 0;
for (int i=0; i<source.length; i++) {
if (source[i] == 2) {
numberOfTwos++;
} else {
notTwo.append(source[i]);
}
}
... simply append `numberOfTwo` 0s to the list, and then turn it into an array
You see: you are nesting two for-loops, and you are repeatedly copying around elements. That is inefficient, hard to understand, and no matter how you do it: way too complicated. As shown: using a second list/array it is possible to "solve" this problem in a single pass.
After replacing your inner loop with System.arrayCopy the code should look like:
int[] numbers = { 1, 2, 3, 2, 2, 4, 5 };
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == 2) {
System.arraycopy(numbers, i + 1, numbers, i, numbers.length - 1 - i);
numbers[numbers.length - 1] = 0;
i--;
}
}
Is there a algorithm to determine a knapsack which has an exact weight W? I.e. it's like the normal 0/1 knapsack problem with n items each having weight w_i and value v_i. Maximise the value of all the items, however the total weight of the items in the knapsack need to have exactly weight W!
I know the "normal" 0/1 knapsack algorithm but this could also return a knapsack with less weight but higher value. I want to find the highest value but exact W weight.
Here is my 0/1 knapsack implementation:
public class KnapSackTest {
public static void main(String[] args) {
int[] w = new int[] {4, 1, 5, 8, 3, 9, 2}; //weights
int[] v = new int[] {2, 12, 8, 9, 3, 4, 3}; //values
int n = w.length;
int W = 15; // W (max weight)
int[][] DP = new int[n+1][W+1];
for(int i = 1; i < n+1; i++) {
for(int j = 0; j < W+1; j++) {
if(i == 0 || j == 0) {
DP[i][j] = 0;
} else if (j - w[i-1] >= 0) {
DP[i][j] = Math.max(DP[i-1][j], DP[i-1][j - w[i-1]] + v[i-1]);
} else {
DP[i][j] = DP[i-1][j];
}
}
}
System.out.println("Result: " + DP[n][W]);
}
}
This gives me:
Result: 29
(Just ask if anything is unclear in my question!)
Actually, the accepted answer is wrong, as found by #Shinchan in the comments.
You get exact weight knapsack by changing only the initial dp state, not the algorithm itself.
The initialization, instead of:
if(i == 0 || j == 0) {
DP[i][j] = 0;
}
should be:
if (j == 0) {
DP[i][j] = 0;
} else if (i == 0 && j > 0) { // obviously `&& j > 0` is not needed, but for clarity
DP[i][j] = -inf;
}
The rest stays as in your question.
By simply setting DP[i][j] = -infinity in your last else clause it will do the trick.
The ides behind it is to slightly change the recursive formula definition to calculate:
Find the maximal value with exactly weight j up to item i.
Now, the induction hypothesis will change, and the proof of correctness will be very similar to regular knapsack with the following modification:
DP[i][j-weight[i]] is now the maximal value that can be constructed with exactly j-weight[i], and you can either take item i, giving value of DP[i][j-weight[i]], or not taking it, giving value of DP[i-1][j] - which is the maximal value when using exactly weight j with first i-1 items.
Note that if for some reason you cannot construct DP[i][j], you will never use it, as the value -infinity will always discarded when looking for MAX.
I'm writing a function that tries to find the middle of a 2d array, and here's what I have so far:
int findMiddle(int[][] grid,int [] m) {
int[] list = new int[grid.length*grid[0].length];
int listPos = 0;
for(int i = 0 ; i < grid.length; i++) {
for(int j = 0; j < grid.length; j++) {
list[listPos++] = grid[i][j];
}
}
int middle = m.length/2;
if (m.length%2 == 1) {
return m[middle];
} else {
return (m[middle-1] + m[middle]) / 2.0;
}
}
Suppose I have an array of
{{0, 1, 2, 3},
{4, 5, 6, 7},
{8, 9, 0, 1}}
It should return 6, as it is integer division.
Also, the definition of middle in this code is the middle integer of the whole original array (needless to say if it is sorted or not).
How would I do this? ( my code also doesn't compile)
This compiles, and will give you the middle number in your sequence, or the average of the middle two if it splits the middle:
static double findMiddle(int[][] grid) {
int[] list = new int[grid.length*grid[0].length];
int listPos = 0;
for(int i = 0 ; i < grid.length; i++) {
for(int j = 0; j < grid[i].length; j++) {
list[listPos++] = grid[i][j];
}
}
int middle = list.length/2;
if ((list.length%2) == 1) {
return list[middle];
}
return (list[middle-1] + list[middle]) / 2.0;
}
However, I suspect you'll want to sort you numbers after you combine them into a single array, before you find the middle numbers. (as piyush121 commented)
Assuming your definition of 'median' is correct (the middle number of an odd length set or the average of the two middle numbers of an even length set), and if grid[][] is sorted, and if grid[][] is a square array (i.e. grid.length = grid[i].length for all i in 0..length-1, then you don't need to copy data to another array. The following should suffice:
static int findMiddle(int[][] grid) {
int l = grid.length;
if (l%2 == 1) {
return grid[l/2][l/2];
} else {
return (grid[l/2-1][l-1]+grid[l/2][0])/2;
};
Looking at your existing code it seems you are defining 'median' as the middle value in the matrix if all values were put into a single row-wise list. In other words you don't need to cope with odd numbers of rows (when two numbers from the same column are in the middle) or odd numbers of rows and columns (when there are four numbers in the middle).
If that definition is correct then you can cope with all the complexity of uneven rows by streaming all values and then selecting the middle ones.
For your interest, here's a Java 8 solution that does that:
int[] flat = Arrays.stream(grid).flatMapToInt(Arrays::stream).toArray();
double middle = Arrays.stream(flat).skip(flat.length / 2).limit(1 + flat.length % 2)
.average().getAsDouble();
I spend last 5 hours looking at so many videos and readings (cormen included) and i finally decided to write my own heapsort to test it out. I am basically taking some inputs from standard input and storing them in an array and then i will use heapsort to sort them.
Following is my code
public static void buildHeap(int[] A)
{
n = A.length - 1;
for(int i = n/2; i>0; i--)
{
maxHeapify(A,i);
}
}
public static void maxHeapify(int[] A, int i)
{
int left = 2*i;
int right = 2*i + 1;
int largest = 0;
if(left <= n && A[left] > A[i])
{
largest=left;
}
else
{
largest=i;
}
if(right <= n && A[right] > A[largest]){
largest=right;
}
if(largest!=i){
int temp = A[i];
A[i] = A[largest];
A[largest] = temp;
maxHeapify(A, largest);
}
}
My Array Input is : 3,5,8,7,1,13,11,15,6 Output is:
3,15,13,11,6,8,5,7,1
The output is obviously wrong as the first index should contain the highest value 15.
So then i decided to take the good old route of taking a pen and a notebook and tracing the code and realized that in the buildHeap the i should be n-1/2 . However it also did not give me the correct output. I am really lost now and frustrated. Can anyone shed light as to what i am doing wrong?
Your index calculations are off:
int left = 2*i;
int right = 2*i + 1;
If i is 0, then we want left and right to be 1 and 2. If i is 1, then left and right should be 3 and 4, and so on. The calculations should be:
int left = 2*i + 1;
int right = 2*i + 2;
Also,
for(int i = n/2; i>0; i--)
The condition is i > 0. The body of the loop will only run when i > 0, so the element at index 0 (i.e. the first one) won't get moved. The condition should be i >= 0.