Initializing std::memset - c++
I'm using std::memset to solve a LeetCode problem copied here. Currently, map_cherries has been initialized as:
map_cherries[70][70][70] = {}
...
std::memset(map_cherries, -1, sizeof(map_cherries));
Is there a way to set up dimensions and values of map_cherries at the same time, or maybe any better/alternative way to do that? Thank you!
Problem
Given a rows x cols matrix grid representing a field of cherries.
Each cell in grid represents the number of cherries that you can
collect.
You have two robots that can collect cherries for you, Robot #1 is
located at the top-left corner (0,0), and Robot #2 is located at the
top-right corner (0, cols-1) of the grid.
Return the maximum number of cherries collection using both robots by
following the rules below:
From a cell (i,j), robots can move to cell (i+1, j-1) , (i+1, j) or (i+1, j+1).
When any robot is passing through a cell, It picks it up all cherries, and the cell becomes an empty cell (0).
When both robots stay on the same cell, only one of them takes the cherries.
Both robots cannot move outside of the grid at any moment.
Both robots should reach the bottom row in the grid.
Example 1:
Input: grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]
Output: 24
Explanation: Path of robot #1 and #2 are described in color green and
blue respectively.
Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.
Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.
Total of cherries: 12 + 12 = 24.
Example 2:
Input: grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]
Output: 28
Explanation: Path of robot #1 and #2 are described in
color green and blue respectively.
Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.
Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.
Total of cherries: 17 + 11 = 28.
Constraints:
rows == grid.length
cols == grid[i].length
2 <= rows, cols <= 70
0 <= grid[i][j] <= 100
Attempt
#include <cstdint>
#include <vector>
#include <cstring>
struct Solution {
int map_cherries[70][70][70] = {};
int cherryPickup(std::vector<std::vector<int>>& grid) {
std::memset(map_cherries, -1, sizeof(map_cherries));
const std::size_t row_length = grid.size();
const std::size_t col_length = grid[0].size();
return depth_first_search(grid, row_length, col_length, 0, 0, col_length - 1);
}
private:
int depth_first_search(
std::vector<std::vector<int>>& grid,
const std::size_t row_length,
const std::size_t col_length,
int row,
int left_robot,
int right_robot
) {
if (row == row_length) {
return 0;
}
if (map_cherries[row][left_robot][right_robot] != -1) {
return map_cherries[row][left_robot][right_robot];
}
int max_cherries = 0;
for (int left = -1; left < 2; left++) {
for (int right = -1; right < 2; right++) {
const int curr_left_robot = left_robot + left;
const int curr_right_robot = right_robot + right;
if (curr_left_robot > -1 and curr_left_robot < col_length and curr_right_robot > -1 and curr_right_robot < col_length) {
max_cherries = std::max(max_cherries, depth_first_search(
grid,
row_length,
col_length,
row + 1,
curr_left_robot,
curr_right_robot
));
}
}
}
int total_cherries = grid[row][left_robot];
if (left_robot != right_robot) {
total_cherries += grid[row][right_robot];
}
total_cherries += max_cherries;
return map_cherries[row][left_robot][right_robot] = total_cherries;
}
};
Inputs
[[3,1,1],[2,5,1],[1,5,5],[2,1,1]]
[[1,0,0,3],[0,0,0,3],[0,0,3,3],[9,0,3,3]]
[[1,10,0,3,86,40],[0,0,0,3,86,40],[0,0,3,3,86,40],[9,0,3,3,86,40], [1,0,40,3,86,40],[0,22,0,3,86,40],[99,0,3,3,86,40],[9,0,3,3,86,40]]
Outputs
24
22
819
References
Problem
Discuss
Solution
One way would be like this:
auto map_cherries = std::vector(70, std::vector(70, std::vector(70, -1)));
Only works starting from c++17.
Related
how to calculate multiset of elements given probability on each element?
let say I have a total number tN = 12 and a set of elements elem = [1,2,3,4] and a prob for each element to be taken prob = [0.0, 0.5, 0.75, 0.25] i need to get a random multiset of these elements, such as the taken elements reflects the prob the sum of each elem is tN with the example above, here's some possible outcome: 3 3 2 4 2 3 2 3 2 3 4 2 3 2 2 3 3 2 3 2 3 2 2 at the moment, maxtN will be 64, and elements the one above (1,2,3,4). is this a Knapsack problem? how would you easily resolve it? both "on the fly" or "pre-calculate" approch will be allowed (or at least, depends by the computation time). I'm doing it for a c++ app. Mission: don't need to have exactly the % in the final seq. Just to give more possibility to an elements to be in the final seq due to its higher prob. In few words: in the example, i prefer get seq with more 3-2 rather than 4, and no 1. Here's an attempt to select elements with its prob, on 10 takes: Randomizer randomizer; int tN = 12; std::vector<int> elem = {2, 3, 4}; std::vector<float> prob = {0.5f, 0.75f, 0.25f}; float probSum = std::accumulate(begin(prob), end(prob), 0.0f, std::plus<float>()); std::vector<float> probScaled; for (size_t i = 0; i < prob.size(); i++) { probScaled.push_back((i == 0 ? 0.0f : probScaled[i - 1]) + (prob[i] / probSum)); } for (size_t r = 0; r < 10; r++) { float rnd = randomizer.getRandomValue(); int index = 0; for (size_t i = 0; i < probScaled.size(); i++) { if (rnd < probScaled[i]) { index = i; break; } } std::cout << elem[index] << std::endl; } which gives, for example, this choice: 3 3 2 2 4 2 2 4 3 3 Now i just need to build a multiset which sum up to tN. Any tips?
Largest Area Axis-Aligned Rectangle Inside Convex Polygon [duplicate]
Given an NxN binary matrix (containing only 0's or 1's), how can we go about finding largest rectangle containing all 0's? Example: I 0 0 0 0 1 0 0 0 1 0 0 1 II->0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 <--IV 0 0 1 0 0 0 IV For the above example, it is a 6×6 binary matrix. the return value in this case will be Cell 1:(2, 1) and Cell 2:(4, 4). The resulting sub-matrix can be square or rectangular. The return value can also be the size of the largest sub-matrix of all 0's, in this example 3 × 4.
Here's a solution based on the "Largest Rectangle in a Histogram" problem suggested by #j_random_hacker in the comments: [Algorithm] works by iterating through rows from top to bottom, for each row solving this problem, where the "bars" in the "histogram" consist of all unbroken upward trails of zeros that start at the current row (a column has height 0 if it has a 1 in the current row). The input matrix mat may be an arbitrary iterable e.g., a file or a network stream. Only one row is required to be available at a time. #!/usr/bin/env python from collections import namedtuple from operator import mul Info = namedtuple('Info', 'start height') def max_size(mat, value=0): """Find height, width of the largest rectangle containing all `value`'s.""" it = iter(mat) hist = [(el==value) for el in next(it, [])] max_size = max_rectangle_size(hist) for row in it: hist = [(1+h) if el == value else 0 for h, el in zip(hist, row)] max_size = max(max_size, max_rectangle_size(hist), key=area) return max_size def max_rectangle_size(histogram): """Find height, width of the largest rectangle that fits entirely under the histogram. """ stack = [] top = lambda: stack[-1] max_size = (0, 0) # height, width of the largest rectangle pos = 0 # current position in the histogram for pos, height in enumerate(histogram): start = pos # position where rectangle starts while True: if not stack or height > top().height: stack.append(Info(start, height)) # push elif stack and height < top().height: max_size = max(max_size, (top().height, (pos - top().start)), key=area) start, _ = stack.pop() continue break # height == top().height goes here pos += 1 for start, height in stack: max_size = max(max_size, (height, (pos - start)), key=area) return max_size def area(size): return reduce(mul, size) The solution is O(N), where N is the number of elements in a matrix. It requires O(ncols) additional memory, where ncols is the number of columns in a matrix. Latest version with tests is at https://gist.github.com/776423
Please take a look at Maximize the rectangular area under Histogram and then continue reading the solution below. Traverse the matrix once and store the following; For x=1 to N and y=1 to N F[x][y] = 1 + F[x][y-1] if A[x][y] is 0 , else 0 Then for each row for x=N to 1 We have F[x] -> array with heights of the histograms with base at x. Use O(N) algorithm to find the largest area of rectangle in this histogram = H[x] From all areas computed, report the largest. Time complexity is O(N*N) = O(N²) (for an NxN binary matrix) Example: Initial array F[x][y] array 0 0 0 0 1 0 1 1 1 1 0 1 0 0 1 0 0 1 2 2 0 2 1 0 0 0 0 0 0 0 3 3 1 3 2 1 1 0 0 0 0 0 0 4 2 4 3 2 0 0 0 0 0 1 1 5 3 5 4 0 0 0 1 0 0 0 2 6 0 6 5 1 For x = N to 1 H[6] = 2 6 0 6 5 1 -> 10 (5*2) H[5] = 1 5 3 5 4 0 -> 12 (3*4) H[4] = 0 4 2 4 3 2 -> 10 (2*5) H[3] = 3 3 1 3 2 1 -> 6 (3*2) H[2] = 2 2 0 2 1 0 -> 4 (2*2) H[1] = 1 1 1 1 0 1 -> 4 (1*4) The largest area is thus H[5] = 12
Here is a Python3 solution, which returns the position in addition to the area of the largest rectangle: #!/usr/bin/env python3 import numpy s = '''0 0 0 0 1 0 0 0 1 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0''' nrows = 6 ncols = 6 skip = 1 area_max = (0, []) a = numpy.fromstring(s, dtype=int, sep=' ').reshape(nrows, ncols) w = numpy.zeros(dtype=int, shape=a.shape) h = numpy.zeros(dtype=int, shape=a.shape) for r in range(nrows): for c in range(ncols): if a[r][c] == skip: continue if r == 0: h[r][c] = 1 else: h[r][c] = h[r-1][c]+1 if c == 0: w[r][c] = 1 else: w[r][c] = w[r][c-1]+1 minw = w[r][c] for dh in range(h[r][c]): minw = min(minw, w[r-dh][c]) area = (dh+1)*minw if area > area_max[0]: area_max = (area, [(r-dh, c-minw+1, r, c)]) print('area', area_max[0]) for t in area_max[1]: print('Cell 1:({}, {}) and Cell 2:({}, {})'.format(*t)) Output: area 12 Cell 1:(2, 1) and Cell 2:(4, 4)
Here is J.F. Sebastians method translated into C#: private Vector2 MaxRectSize(int[] histogram) { Vector2 maxSize = Vector2.zero; int maxArea = 0; Stack<Vector2> stack = new Stack<Vector2>(); int x = 0; for (x = 0; x < histogram.Length; x++) { int start = x; int height = histogram[x]; while (true) { if (stack.Count == 0 || height > stack.Peek().y) { stack.Push(new Vector2(start, height)); } else if(height < stack.Peek().y) { int tempArea = (int)(stack.Peek().y * (x - stack.Peek().x)); if(tempArea > maxArea) { maxSize = new Vector2(stack.Peek().y, (x - stack.Peek().x)); maxArea = tempArea; } Vector2 popped = stack.Pop(); start = (int)popped.x; continue; } break; } } foreach (Vector2 data in stack) { int tempArea = (int)(data.y * (x - data.x)); if(tempArea > maxArea) { maxSize = new Vector2(data.y, (x - data.x)); maxArea = tempArea; } } return maxSize; } public Vector2 GetMaximumFreeSpace() { // STEP 1: // build a seed histogram using the first row of grid points // example: [true, true, false, true] = [1,1,0,1] int[] hist = new int[gridSizeY]; for (int y = 0; y < gridSizeY; y++) { if(!invalidPoints[0, y]) { hist[y] = 1; } } // STEP 2: // get a starting max area from the seed histogram we created above. // using the example from above, this value would be [1, 1], as the only valid area is a single point. // another example for [0,0,0,1,0,0] would be [1, 3], because the largest area of contiguous free space is 3. // Note that at this step, the heigh fo the found rectangle will always be 1 because we are operating on // a single row of data. Vector2 maxSize = MaxRectSize(hist); int maxArea = (int)(maxSize.x * maxSize.y); // STEP 3: // build histograms for each additional row, re-testing for new possible max rectangluar areas for (int x = 1; x < gridSizeX; x++) { // build a new histogram for this row. the values of this row are // 0 if the current grid point is occupied; otherwise, it is 1 + the value // of the previously found historgram value for the previous position. // What this does is effectly keep track of the height of continous avilable spaces. // EXAMPLE: // Given the following grid data (where 1 means occupied, and 0 means free; for clairty): // INPUT: OUTPUT: // 1.) [0,0,1,0] = [1,1,0,1] // 2.) [0,0,1,0] = [2,2,0,2] // 3.) [1,1,0,1] = [0,0,1,0] // // As such, you'll notice position 1,0 (row 1, column 0) is 2, because this is the height of contiguous // free space. for (int y = 0; y < gridSizeY; y++) { if(!invalidPoints[x, y]) { hist[y] = 1 + hist[y]; } else { hist[y] = 0; } } // find the maximum size of the current histogram. If it happens to be larger // that the currently recorded max size, then it is the new max size. Vector2 maxSizeTemp = MaxRectSize(hist); int tempArea = (int)(maxSizeTemp.x * maxSizeTemp.y); if (tempArea > maxArea) { maxSize = maxSizeTemp; maxArea = tempArea; } } // at this point, we know the max size return maxSize; } A few things to note about this: This version is meant for use with the Unity API. You can easily make this more generic by replacing instances of Vector2 with KeyValuePair. Vector2 is only used for a convenient way to store two values. invalidPoints[] is an array of bool, where true means the grid point is "in use", and false means it is not.
Solution with space complexity O(columns) [Can be modified to O(rows) also] and time complexity O(rows*columns) public int maximalRectangle(char[][] matrix) { int m = matrix.length; if (m == 0) return 0; int n = matrix[0].length; int maxArea = 0; int[] aux = new int[n]; for (int i = 0; i < n; i++) { aux[i] = 0; } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { aux[j] = matrix[i][j] - '0' + aux[j]; maxArea = Math.max(maxArea, maxAreaHist(aux)); } } return maxArea; } public int maxAreaHist(int[] heights) { int n = heights.length; Stack<Integer> stack = new Stack<Integer>(); stack.push(0); int maxRect = heights[0]; int top = 0; int leftSideArea = 0; int rightSideArea = heights[0]; for (int i = 1; i < n; i++) { if (stack.isEmpty() || heights[i] >= heights[stack.peek()]) { stack.push(i); } else { while (!stack.isEmpty() && heights[stack.peek()] > heights[i]) { top = stack.pop(); rightSideArea = heights[top] * (i - top); leftSideArea = 0; if (!stack.isEmpty()) { leftSideArea = heights[top] * (top - stack.peek() - 1); } else { leftSideArea = heights[top] * top; } maxRect = Math.max(maxRect, leftSideArea + rightSideArea); } stack.push(i); } } while (!stack.isEmpty()) { top = stack.pop(); rightSideArea = heights[top] * (n - top); leftSideArea = 0; if (!stack.isEmpty()) { leftSideArea = heights[top] * (top - stack.peek() - 1); } else { leftSideArea = heights[top] * top; } maxRect = Math.max(maxRect, leftSideArea + rightSideArea); } return maxRect; } But I get Time Limite exceeded excpetion when I try this on LeetCode. Is there any less complex solution?
I propose a O(nxn) method. First, you can list all the maximum empty rectangles. Empty means that it covers only 0s. A maximum empty rectangle is such that it cannot be extended in a direction without covering (at least) one 1. A paper presenting a O(nxn) algorithm to create such a list can be found at www.ulg.ac.be/telecom/rectangles as well as source code (not optimized). There is no need to store the list, it is sufficient to call a callback function each time a rectangle is found by the algorithm, and to store only the largest one (or choose another criterion if you want). Note that a proof exists (see the paper) that the number of largest empty rectangles is bounded by the number of pixels of the image (nxn in this case). Therefore, selecting the optimal rectangle can be done in O(nxn), and the overall method is also O(nxn). In practice, this method is very fast, and is used for realtime video stream analysis.
Here is a version of jfs' solution, which also delivers the position of the largest rectangle: from collections import namedtuple from operator import mul Info = namedtuple('Info', 'start height') def max_rect(mat, value=0): """returns (height, width, left_column, bottom_row) of the largest rectangle containing all `value`'s. Example: [[0, 0, 0, 0, 0, 0, 0, 0, 3, 2], [0, 4, 0, 2, 4, 0, 0, 1, 0, 0], [1, 0, 1, 0, 0, 0, 3, 0, 0, 4], [0, 0, 0, 0, 4, 2, 0, 0, 0, 0], [0, 0, 0, 2, 0, 0, 0, 0, 0, 0], [4, 3, 0, 0, 1, 2, 0, 0, 0, 0], [3, 0, 0, 0, 2, 0, 0, 0, 0, 4], [0, 0, 0, 1, 0, 3, 2, 4, 3, 2], [0, 3, 0, 0, 0, 2, 0, 1, 0, 0]] gives: (3, 4, 6, 5) """ it = iter(mat) hist = [(el==value) for el in next(it, [])] max_rect = max_rectangle_size(hist) + (0,) for irow,row in enumerate(it): hist = [(1+h) if el == value else 0 for h, el in zip(hist, row)] max_rect = max(max_rect, max_rectangle_size(hist) + (irow+1,), key=area) # irow+1, because we already used one row for initializing max_rect return max_rect def max_rectangle_size(histogram): stack = [] top = lambda: stack[-1] max_size = (0, 0, 0) # height, width and start position of the largest rectangle pos = 0 # current position in the histogram for pos, height in enumerate(histogram): start = pos # position where rectangle starts while True: if not stack or height > top().height: stack.append(Info(start, height)) # push elif stack and height < top().height: max_size = max(max_size, (top().height, (pos - top().start), top().start), key=area) start, _ = stack.pop() continue break # height == top().height goes here pos += 1 for start, height in stack: max_size = max(max_size, (height, (pos - start), start), key=area) return max_size def area(size): return size[0] * size[1]
To be complete, here's the C# version which outputs the rectangle coordinates. It's based on dmarra's answer but without any other dependencies. There's only the function bool GetPixel(int x, int y), which returns true when a pixel is set at the coordinates x,y. public struct INTRECT { public int Left, Right, Top, Bottom; public INTRECT(int aLeft, int aTop, int aRight, int aBottom) { Left = aLeft; Top = aTop; Right = aRight; Bottom = aBottom; } public int Width { get { return (Right - Left + 1); } } public int Height { get { return (Bottom - Top + 1); } } public bool IsEmpty { get { return Left == 0 && Right == 0 && Top == 0 && Bottom == 0; } } public static bool operator ==(INTRECT lhs, INTRECT rhs) { return lhs.Left == rhs.Left && lhs.Top == rhs.Top && lhs.Right == rhs.Right && lhs.Bottom == rhs.Bottom; } public static bool operator !=(INTRECT lhs, INTRECT rhs) { return !(lhs == rhs); } public override bool Equals(Object obj) { return obj is INTRECT && this == (INTRECT)obj; } public bool Equals(INTRECT obj) { return this == obj; } public override int GetHashCode() { return Left.GetHashCode() ^ Right.GetHashCode() ^ Top.GetHashCode() ^ Bottom.GetHashCode(); } } public INTRECT GetMaximumFreeRectangle() { int XEnd = 0; int YStart = 0; int MaxRectTop = 0; INTRECT MaxRect = new INTRECT(); // STEP 1: // build a seed histogram using the first row of grid points // example: [true, true, false, true] = [1,1,0,1] int[] hist = new int[Height]; for (int y = 0; y < Height; y++) { if (!GetPixel(0, y)) { hist[y] = 1; } } // STEP 2: // get a starting max area from the seed histogram we created above. // using the example from above, this value would be [1, 1], as the only valid area is a single point. // another example for [0,0,0,1,0,0] would be [1, 3], because the largest area of contiguous free space is 3. // Note that at this step, the heigh fo the found rectangle will always be 1 because we are operating on // a single row of data. Tuple<int, int> maxSize = MaxRectSize(hist, out YStart); int maxArea = (int)(maxSize.Item1 * maxSize.Item2); MaxRectTop = YStart; // STEP 3: // build histograms for each additional row, re-testing for new possible max rectangluar areas for (int x = 1; x < Width; x++) { // build a new histogram for this row. the values of this row are // 0 if the current grid point is occupied; otherwise, it is 1 + the value // of the previously found historgram value for the previous position. // What this does is effectly keep track of the height of continous avilable spaces. // EXAMPLE: // Given the following grid data (where 1 means occupied, and 0 means free; for clairty): // INPUT: OUTPUT: // 1.) [0,0,1,0] = [1,1,0,1] // 2.) [0,0,1,0] = [2,2,0,2] // 3.) [1,1,0,1] = [0,0,1,0] // // As such, you'll notice position 1,0 (row 1, column 0) is 2, because this is the height of contiguous // free space. for (int y = 0; y < Height; y++) { if (!GetPixel(x, y)) { hist[y]++; } else { hist[y] = 0; } } // find the maximum size of the current histogram. If it happens to be larger // that the currently recorded max size, then it is the new max size. Tuple<int, int> maxSizeTemp = MaxRectSize(hist, out YStart); int tempArea = (int)(maxSizeTemp.Item1 * maxSizeTemp.Item2); if (tempArea > maxArea) { maxSize = maxSizeTemp; maxArea = tempArea; MaxRectTop = YStart; XEnd = x; } } MaxRect.Left = XEnd - maxSize.Item1 + 1; MaxRect.Top = MaxRectTop; MaxRect.Right = XEnd; MaxRect.Bottom = MaxRectTop + maxSize.Item2 - 1; // at this point, we know the max size return MaxRect; } private Tuple<int, int> MaxRectSize(int[] histogram, out int YStart) { Tuple<int, int> maxSize = new Tuple<int, int>(0, 0); int maxArea = 0; Stack<Tuple<int, int>> stack = new Stack<Tuple<int, int>>(); int x = 0; YStart = 0; for (x = 0; x < histogram.Length; x++) { int start = x; int height = histogram[x]; while (true) { if (stack.Count == 0 || height > stack.Peek().Item2) { stack.Push(new Tuple<int, int>(start, height)); } else if (height < stack.Peek().Item2) { int tempArea = (int)(stack.Peek().Item2 * (x - stack.Peek().Item1)); if (tempArea > maxArea) { YStart = stack.Peek().Item1; maxSize = new Tuple<int, int>(stack.Peek().Item2, (x - stack.Peek().Item1)); maxArea = tempArea; } Tuple<int, int> popped = stack.Pop(); start = (int)popped.Item1; continue; } break; } } foreach (Tuple<int, int> data in stack) { int tempArea = (int)(data.Item2 * (x - data.Item1)); if (tempArea > maxArea) { YStart = data.Item1; maxSize = new Tuple<int, int>(data.Item2, (x - data.Item1)); maxArea = tempArea; } } return maxSize; }
An appropriate algorithm can be found within Algorithm for finding the largest inscribed rectangle in polygon (2019). I implemented it in python: import largestinteriorrectangle as lir import numpy as np grid = np.array([[0, 0, 0, 0, 1, 0], [0, 0, 1, 0, 0, 1], [0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1], [0, 0, 1, 0, 0, 0]], "bool") grid = ~grid lir.lir(grid) # [1, 2, 4, 3] the result comes as x, y, width, height
find a selection of elements adjacent sum = 10
Description: Given matrix [x] [y], with x- rows and y- number of columns . Filled random numbers from 0 to 5 inclusive . Description of finding a solution : the solution is considered to be a set of matrix elements that are adjacent to each other ( diagonal neighborhood is not taken into account ) and the sum of the number are 10. Each element of the matrix can be used 1 time for a decision . The solution may have any number of digits. The decision must end any number other than zero . Example: given 0 1 2 3 4 5 1 2 3 4 5 0 2 3 4 5 1 2 Solution 1 : (1 - 2 - 3 - 4) 0 **1** 2 3 4 5 1 **2** 3 4 5 0 2 **3** **4** 5 1 2 i tried to do smth like this, but it is wrong, i dont know when i must stop, Solution it is a class which contains mair of indexes, pls help me. void xxx(int colCount, int rowCount, int currentRow, int currentCol, int** matrix, int sum, Solution *solution, int solCount) { sum += matrix[currentRow][currentCol]; matrix[currentRow][currentCol] = -1; if(sum > 10){ sum - = matrix[currentRow][currentCol]; return; } else if(sum == 10){ solution[solCount].additem(currentRow, currentCol); return xxx(5,5,currentRow - 1, currentCol, matrix, sum, solution, solCount+1); } else { //UP if( currentRow > 0 && matrix [currentRow - 1][currentCol] != -1){ xxx(5,5,currentRow - 1, currentCol, matrix, sum, solution,solCount); } //LEFT if(currentCol > 0 && matrix [currentRow][currentCol-1] != -1){ xxx(5,5,currentRow, currentCol - 1, matrix, sum, solution,solCount); } //DOWN if(currentRow + 1 < colCount && matrix[currentRow + 1][currentCol] != -1){ xxx(5,5,currentRow + 1, currentCol, matrix, sum, solution,solCount); } //RIGHT if(currentCol + 1 < rowCount && matrix[currentRow][currentCol + 1] != -1){ xxx(5,5,currentRow, currentCol + 1, matrix, sum, solution,solCount); } } }
Rotate NxN Matrix Counter(anti)-Clockwise 90 Degress
I have a 2D Matrix M[N][N] that I need to rotate counter-clockwise by 90 degrees. I have seen many answers for clockwise rotation but I cannot find counter-clockwise. How similar are the two operations?
If you reverse the order of each individual row and then taken rows in opposite order from a clockwise rotation, you get a count-clockwise rotation. A B C G D A A D G C F I D E F -> Clockwise -> H E B -> Reverse -> B E H -> Opposite -> B E H G H I I F C Rows C F I Ordering A D G Matrix Counter Clockwise Usually it's easier (and more computationally efficient) to do a clockwise rotation rotation on the original matrix in reverse order if you already have a clockwise rotating algorithm available. 1 2 3 9 8 7 3 6 9 4 5 6 -> Reverse -> 6 5 4 -> Clockwise -> 2 5 8 7 8 9 Indices 3 2 1 1 4 7 Matrix Counter Clockwise You can also just take 3 clockwise rotations to get to a counter clockwise rotation. Though in reality it's usually fairly easy to edit the clockwise algorithm to your purposes directly. So I'd only use the above options if you don't care about efficiency and don't want to work through the logic of changing the direction of rotation.
From row(max), decrementing, fill in the result rows(incrementing index) with the values of that column, one after the other (incrementing). So in a 3 x 3, use (using r, c notation like Excel) (3, 1), (3, 2), (3, 3), (2, 1), (2, 2), (2, 3), etc.
You can just take the transpose 3 times, if you are using a particular matrix library
OK. let us say N =2 to be simple: 1 2 3 4 counter-clockwise 90 degree means that it will become: 2 4 1 3 We have the following rules: 1 last column from top to bottom of original matrix becomes first row of rotated matrix from left to right 2 first column of original matrix becomes last row of rotated matrix 3 same rules apply to other columns of original matrix You can easily code this out. Another way to do is to first do a transpose on the matrix then reverse the order of all rows.
public static void main(String[] args) { int[][] matrix = createAMatrix(3,3); List<Stack<Integer>> tiltedMatrix = tiltMatrixBy90Now(matrix, 3); int[][] newMatrix = new int[3][3]; for(int i = 0; i < 3; i ++) { for(int j = 0; j < 3; j ++) { newMatrix[i][j] = tiltedMatrix.get(j).pop(); } } //print new matrix for(int i = 0; i < 3; i ++) { for(int j = 0; j < 3; j ++) { System.out.print(newMatrix[i][j]+" "); } System.out.println(); } } private static List<Stack<Integer>> tiltMatrixBy90Now(int[][] matrix , long order) { List<Stack<Integer>> stackList = new ArrayList<>(); //filling the stack for(int i = 0; i< order ; i++) { stackList.add(new Stack<Integer>()); } for(int i = 0; i < order; i ++) { for(int j = 0; j < order; j ++) { stackList.get(i).push(matrix[i][j]); } } return stackList; } private static int[][] createAMatrix(final int a, final int b){ int counter = 1; int[][] matrix = new int[a][b]; Scanner scanner = new Scanner(System.in); while(counter <= a*b) { for(int i = 0; i < a; i ++) { for(int j = 0; j < b; j ++) { matrix[i][j] = scanner.nextInt(); counter++; } } } return matrix; } /* Input matrix (3 by 3) 1 2 3 4 5 6 7 8 9 Output matrix (3 by 3): 3 6 9 2 5 8 1 4 7 Code walk through as text explanation Create a matrix , in above code It is 3*3 matrix Creating 3 stacks from each row of 3*3 matrix Pop from each stack one by one in parallel and and re-creating a matrix. Printing the new tilted matrix by 90 degree(Anticlockwise). */
Partitioning arrays by index
I am fairly new to C++, and am struggling through a problem that seems to have a solid solution but I just can't seem to find it. I have a contiguous array of ints starting at zero: int i[6] = { 0, 1, 2, 3, 4, 5 }; // this is actually from an iterator I would like to partition the array into groups of three. The design is to have two methods, j and k, such that given an i they will return the other two elements from the same group of three. For example: i j(i) k(i) 0 1 2 1 0 2 2 0 1 3 4 5 4 3 5 5 3 4 The solution seems to involve summing the i with its value mod three and either plus or minus one, but I can't quite seem to work out the logic.
This should work: int d = i % 3; int j = i - d + ( d == 0 ); int k = i - d + 2 - ( d == 2 ); or following statement for k could be more readable: int k = i - d + ( d == 2 ? 1 : 2 );
This should do it: int j(int i) { int div = i / 3; if (i%3 != 0) return 3*div; else return 3*div+1; } int k(int i) { int div = i / 3; if (i%3 != 2) return 3*div+2; else return 3*div+1; } Test. If you want shorter functions: int j(int i) { return i/3*3 + (i%3 ? 0 : 1); } int k(int i) { return i/3*3 + (i%3-2 ? 2 : 1); }
Well, first, notice that j(i) == j(3+i) == j(6+i) == j(9+i) == ... k(i) == k(3+i) == k(6+i) == k(9+i) == ... In other words, you only need to find a formula for j(i), i = 0, 1, 2 k(i), i = 0, 1, 2 and then for the rest of the cases simply plug in i mod 3. From there, you'll have trouble finding a simple formula because your "rotation" isn't standard. Instead of i j(i) k(i) 0 1 2 1 2 0 2 0 1 for which the formula would have been j(i) = (i + 1) % 3 k(i) = (i + 2) % 3 you have i j(i) k(i) 0 1 2 1 0 1 2 0 2 for which the only formula I can think of at the moment is j(i) = (i == 0 ? 1 : 0) k(i) = (i == 1 ? 1 : 2)
If the values of your array (let's call it arr, not i in order to avoid confusion with the index i) do not coincide with their respective index, you have to perform a reverse lookup to figure out their index first. I propose using an std::map<int,size_t> or an std::unordered_map<int,size_t>. That structure reflects the inverse of arr and you can extra the index for a particular value with its subscript operator or the at member function. From then, you can operate purely on the indices, and use modulo (%) to access the previous and the next element as suggested in the other answers.