Wordsearch with directions saved in int array - c++

I'm trying to develop a wordsearch which finds the word "OIE" (indicating how many times appears), based in an integer unidimensional array that saves the directions (8), but I get strange errors when I run this (and incorrect outputs).
This is the code:
int arrf[8] = {0, -1, -1, -1, 0, 1, 1, 1};
int arrc[8] = {-1, -1, 0, 1, 1, 1, 0,-1};
char s[] = "OIE";
int main() {
int n, m;
while (cin >> n >> m) {
int res = 0;
vector<vector<char> > S(n, vector<char>(m));
for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) cin >> S[i][j];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
for (int d = 0; d < 8; ++d) {
bool trobat = true;
for (int h = 0; h < 3 and trobat; ++h) {
int f = i + arrf[d], c = j + arrc[d];
if (f < 0 || f >= n || c < 0 || c >= m || S[f][c] != s[h])
trobat = false;
}
if (trobat) res++;
}
}
}
cout << res << endl;
}
}
Could somebody help me to fix this? I would appreciate.
Regards.

One error is that this line
int f = i + arrf[d], c = j + arrc[d];
should be
int f = i + h*arrf[d], c = j + h*arrc[d];
With your code it doesn't matter how many times you go round the inner loop you are still checking the same position.

Related

How is uncommenting a cout line changing the final answer?

I have the following code
#include <bits/stdc++.h>
using namespace std;
int main() {
int r = 0, c = 0;
int best = 0;
cin >> r >> c;
int myGrid[r + 2][c + 2] = {};
for (int i = 1; i < r + 1; i++) {
for (int j = 1; j < c + 1; j++) {
cin >> myGrid[i][j];
}
}
bool stillIn = false;
int di[] = {-1,-1, -1, 0, 0, 1, 1, 1};
int dj[] = {-1,0, 1, -1, 1, -1, 0, 1};
for (int i = 1; i < r + 1; i++) {
for (int J = 1; J < c + 1; J++) {
stillIn = false;
for (int k = 0; k < 8; k++) {
// cout << myGrid[i][J] << " " << endl;
if (myGrid[i][J] == myGrid[di[k]][dj[k]]) {
stillIn = true;
}
}
if (stillIn == true) {
best = myGrid[i][J];
}
}
}
cout << best;
return 0;
}
If I run the code with the following input:
4 3
0 1 0
1 2 0
1 5 1
2 3 4
It prints 4. However, if I uncomment line 28, which is
// cout << myGrid[i][J] << " " << endl;
Then it gives me 1, which is the correct answer. Why is this happening!? How does using cout change the final answer?
Thanks in advance for any help.
You have undefined behavior(UB) because you are indexing out of bounds on this line
myGrid[di[k]][dj[k]]
because di and dj contain values of -1.
If you have UB, then anything can happen, such as a cout statement exisiting or not, changing the program in weird ways.
Also variable length arrays are not allowed in standard c++.

having trouble making a function to find the determinant of a matrix

Probably a simple fix, but I keep getting 0 as the determinate when I should be getting 22, I have to use dynamic memory allocation as well. Might be some problem with using floats as I am not completely familiar with how they work with pointers. Honestly don't know what could be causing the function to output a zero.
cpp.sh link to test: http://cpp.sh/5bu2v
#include <iostream>
#include <math.h>
using namespace std;
float determinant(float *mat1, int &rows1)
{
float s = 1, D = 0;
float *temp = new float[rows1 * rows1];
int i, j, m, n, c;
if (rows1 == 1)
{
return (*(mat1 + 0 * rows1 + 0));
}
else
{
D = 0;
for (c = 0; c < rows1; c++)
{
m = 0;
n = 0;
for (i = 0; i < rows1; i++)
{
for (j = 0; j < rows1; j++)
{
*(temp + i * rows1 + j) = 0;
if (i != 0 && j != c)
{
*(temp + m * rows1 + n) = *(mat1 + i * rows1 + j);
if (n < (rows1 - 2))
n++;
else
{
n = 0;
m++;
}
}
}
}
int V1 = rows1 - 1;
D = D + s * (*(mat1 + 0 * rows1 + c) * determinant(temp, V1));
s = -1 * s;
}
}
return (D);
}
int main()
{
int i, j;
int n = 3;
int matrix[10][10] = {{1, 2, 3},
{0, 4, 5},
{1, 0, 6}};
float *mat1 = new float[n * n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
*(mat1 + i * n + j) = matrix[i][j];
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
cout << matrix[i][j] << " ";
cout << endl;
}
cout << "Determinant of the matrix is " << determinant(mat1, n);
return 0;
}
Your first call into determinant, mat is a 3x3 matrix stored in a 1 dimensional array. Visualize it like this:
A B C
D E F
G H I
You create another 3x3 matrix, temp.
You series of loops to fill the temp matrix exclude the first row and column c, so it ends up looking like this the first time thru:
D E 0
G H 0
0 0 0
This gets passed to determinant, which is expecting a 2x2 matrix. Since you've passed it something else, what the recursive call sees is
D E
0 G
When you construct temp you need to do it with the smaller matrix size, not the source size.

Printing out the longest increasing path in a matrix

I made a similar post on here but didn't get any feedback. The problem came from here.
I am trying to simply print out the entries of the longest increasing matrix. I thought I had it figure out when I tried the following matrix:
2 2 1
1 2 1
2 2 1
I got an output of:
1
2
Then when I increased n , m = 4. I got this matrix:
2 2 1 1
2 1 2 2
1 2 2 3
1 2 1 3
And this output for the paths entries:
1
1
2
When it should be just:
1
2
3
Here is my code:
#include <algorithm>
#include <cmath>
#include <list>
#include <vector>
#include <stdio.h>
#include <random>
#include <utility>
#include <iostream>
void printPath(std::vector<int> &numPaths) {
std::sort(numPaths.begin(), numPaths.end());
for(int i = 0; i < numPaths.size(); i++) {
std::cout << numPaths[i] << std::endl;
}
}
int DFS(int i, int j, const std::vector<std::vector<int> > &matrix, std::vector<std::vector<int> > &length) {
std::vector<std::pair<int,int> > dics{{-1,0},{1,0},{0,-1},{0,1}}; // used to check the directions left, right, up, down
std::vector<int> path;
if(length[i][j] == -1) {
int len = 0;
for(auto p: dics) {
int x = i + p.first, y = j + p.second;
if(x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size()) continue; // Check to make sure index is not out of boundary
if(matrix[x][y] > matrix[i][j]) { // compare number
len = std::max(len, DFS(x,y,matrix,length));
}
}
length[i][j] = len + 1;
}
return length[i][j];
}
int longestPath(std::vector<std::vector<int> > matrix) {
int n = matrix[0].size();
if (n == 0) {
return 0;
}
int m = matrix.size();
if (m == 0) {
return 0;
}
std::vector<std::vector<int> > length(m, std::vector<int>(n,-1));
std::vector<int> numPaths;
int len = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int newLen = DFS(i,j,matrix,length);
if(newLen > len) {
numPaths.push_back(matrix[i][j]);
}
len = std::max(len, DFS(i, j, matrix, length));
}
}
printPath(numPaths);
return len;
}
int main() {
// Specify the number of rows and columns of the matrix
int n = 4;
int m = 4;
// Declare random number generator
std::mt19937 gen(10);
std::uniform_int_distribution<> dis(1, 3);
// Fill matrix
std::vector<std::vector<int> > matrix;
for(int i = 0; i < m; i++) {
std::vector<int> row;
for(int j = 0; j < n; j++) {
row.push_back(0);
}
matrix.push_back(row);
}
// Apply random number generator to create matrix
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
matrix[i][j] = dis(gen);
}
}
// Print matrix to see contents
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
//std::vector<std::vector<int> > mat = {{1,2,3}};
int result = longestPath(matrix);
std::cout << "The longest path is " << result << std::endl;
}
I would really appreciate if someone can tell me where I am going wrong.
#include <algorithm>
#include <cmath>
#include <vector>
#include <stdio.h>
#include <random>
#include <utility>
#include <iostream>
#define MATRIX_SIZE 1000
void printPath(std::vector<int> &numPaths) {
std::sort(numPaths.begin(), numPaths.end());
for(int i = 0; i < numPaths.size(); i++) {
std::cout << numPaths[i] << std::endl;
}
}
int DFS(int i, int j, const std::vector<std::vector<int> > &matrix, std::vector<std::vector<int> > &length) {
std::vector<std::pair<int,int> > dics{{-1,0},{1,0},{0,-1},{0,1}}; // used to check the directions left, right, up, down
std::vector<int> path;
if(length[i][j] == -1) {
int len = 0;
for(auto p: dics) {
int x = i + p.first, y = j + p.second;
if(x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size()) continue; // Check to make sure index is not out of boundary
if(matrix[x][y] > matrix[i][j]) { // compare number
len = std::max(len, DFS(x,y,matrix,length));
}
}
length[i][j] = len + 1;
}
return length[i][j];
}
void printMatrix(std::vector<std::vector<int>> &matrix) {
for (int i =0; i < matrix.size(); i++) {
for (int j =0; j < matrix[0].size(); j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
}
std::vector<int> generatePath(int i, int j, const std::vector<std::vector<int>> &matrix, const std::vector<std::vector<int>> &length) {
int max_length = length[i][j];
std::vector<int> path(max_length, 0);
for (int current_length = max_length; current_length >= 1; current_length--) {
std::vector<std::pair<int,int> > dics{{-1,0},{1,0},{0,-1},{0,1}}; // used to check the directions left, right, up, down
int index = max_length - current_length;
for (auto p: dics) {
path[index] = matrix[i][j];
int x = i + p.first, y = j + p.second;
if(x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size()) continue;
if (current_length - length[x][y] == 1) {
i = x;
j = y;
break;
}
}
}
printPath(path);
return path;
}
int longestPath(std::vector<std::vector<int> > matrix) {
int n = matrix[0].size();
if (n == 0) {
return 0;
}
int m = matrix.size();
if (m == 0) {
return 0;
}
std::vector<std::vector<int> > length(m, std::vector<int>(n,-1));
std::vector<int> numPaths;
int len = 0;
int maxRow = 0;
int maxCol = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int currentLength = DFS(i, j, matrix, length);
if (currentLength > len) {
len = currentLength;
maxRow = i;
maxCol = j;
}
}
}
generatePath(maxRow, maxCol, matrix,length);
return len;
}
int main(int argc, char *argv[]) {
std::mt19937 gen(10);
std::uniform_int_distribution<> dis(1, 1000000);
// Fill matrix
std::vector<std::vector<int> > matrix;
for(int i = 0; i < MATRIX_SIZE; i++) {
std::vector<int> row;
for(int j = 0; j < MATRIX_SIZE; j++) {
row.push_back(0);
}
matrix.push_back(row);
}
// Apply random number generator to create matrix
for(int i = 0; i < MATRIX_SIZE; i++) {
for(int j = 0; j < MATRIX_SIZE; j++) {
matrix[i][j] = dis(gen);
}
}
// Print matrix
//printMatrix(matrix);
timespec start, end;
clock_gettime(CLOCK_REALTIME, &start);
printf("the longest path is %d\n", longestPath(matrix));
clock_gettime(CLOCK_REALTIME, &end);
printf("found in %ld micros\n", (end.tv_sec * 1000000 + end.tv_nsec / 1000) - (start.tv_sec * 1000000 + start.tv_nsec / 1000));
return 0;
}
# Print the Longest Increasing Path in a Matrix #
class Solution:
# Possible directions allowed from the given question.
DIRECTIONS = [[1, 0], [-1, 0], [0, 1], [0, -1]]
def longestIncreasingPath(self, matrix):
# From the given question:
# ----- m = rows ----- i
# ----- n = cols ----- j
m = len(matrix)
if m == 0:
return 0
n = len(matrix[0])
if n == 0:
return 0
cache = [[0] * n for _ in range(m)]
longestPath = 0
maximum = 1
for i in range(m):
for j in range(n):
longestPath = self.depthFirstSearch(matrix, i, j, m, n, cache)
maximum = max(maximum, longestPath)
return (cache, maximum)
def depthFirstSearch(self, matrix, i, j, m, n, cache):
if cache[i][j] != 0:
return cache[i][j]
maxPath = 1
for direction in self.DIRECTIONS:
x = direction[0] + i
y = direction[1] + j
if x < 0 or y < 0 or x >= m or y >= n or matrix[x][y] <= matrix[i][j]:
continue
length = 1 + self.depthFirstSearch(matrix, x, y, m, n, cache)
maxPath = max(maxPath, length)
cache[i][j] = maxPath # Save the value at i, j for future usage.
return maxPath
def printPath(self, matrix):
# Check if longestPath is 0.
if not self.longestIncreasingPath(matrix):
return None
length = self.longestIncreasingPath(matrix)[1]
cache = self.longestIncreasingPath(matrix)[0]
# From the given question:
# ----- m = rows ----- i
# ----- n = cols ----- j
m = len(cache)
n = len(cache[0])
location = []
# Traverse the cache to obtain the location of the starting point of the longest increasing path in the matrix.
# Time complexity, T(n) = O(n*m) ----- if not a square matrix.
for i in range(m):
for j in range(n):
if cache[i][j] == length:
location.extend([i, j])
i, j = location[0], location[1]
result = [matrix[i][j]] # The result container is initialised with the element of the matrix at the obtained position
# Time complexity, T(n) = O(4n) ----- where n = length of longest increasing path in the given matrix and the 4 being the length of the DIRECTIONS matrix.
for _ in range(length):
for direction in self.DIRECTIONS:
x = direction[0] + i
y = direction[1] + j
if x < 0 or y < 0 or x >= m or y >= n or cache[i][j] - 1 != cache[x][y]:
continue
result.append(matrix[x][y])
i = x
j = y
return result

Large Numbers Division returns 1 [c++]

I am new here so i am sorry if my question is a kind stupid, but, i was calculating the divisions of two large numbers and storing them in an array, like this:
int det(double M[25][25], int m)
{
/*returns large numbers*/
}
int main()
{
float y[27];
double A[25][25] = {0}, N = 26, D = -134430487042201894894174208;
y[0] = 0;
y[26] = 1;
for (int i = 0; i < N-1; i++)
{
//Reset A[][] to the original
for (int k = 0; k < N-1; k++)
{
for (int J = 0; J < N-1; J++)
{
A[k][J] = m[k][J];
}
}
//Change values of A[j][i]
for (int j = 0; j < N-1; j++)
{
A[j][i] = d[j+1];
}
y[i+1] = det(A,N-1)/D; //Here y returns only 0, 1, 1, 1, 1, ...
}
}D
So, what am i doing wrong? y array returns 0, 1, 1, 1, 1, ... , and it was supposed to not be 1
det(A,N-1) = 7958284334509567005163520
D = -134430487042201894894174208
det(A,N-1)/D = -0.05919999629259109195883585509348322869497780932400145347...
It's not 1.
Thanks!
The function det is returning an int. You are never going to get floating point values from it.

Warnsdorff’s algorithm for Knight’s tour

Please help me with this code. I don't know why is it not printing the output. The code is based on Warnsdorff’s algorithm for Knight’s tour problem. It says "[Error]:Id returned 1 exit status. When I executed it online it sait runtime error. Please help to optimize my code.
#include <bits/stdc++.h>
#define n 8
using namespace std;
static int x_move[n] = {2, 2, -1, -1, 1, 1, -2, -2};
static int y_move[n] = {1, -1, 2, -2, 2, -2, 1, -1};
void print(int arr[][n]) {
for (int i = 0 ; i < n ; ++i) {
for (int j = 0 ; j < n ; ++j)
cout<<arr[i][j]<<" ";
cout<<"\n";
}
}
bool safe(int arr[][n] , int r , int c) {
return (r >= 0 && c >= 0 && r < n && c < n && arr[r][c] == -1);
}
bool neighbour(int r , int c , int sr , int sc) {
for (int i = 0 ; i < n ; ++i)
if ((r + x_move[i] == sr) && (c + x_move[i] == sc))
return true;
return false;
}
int depth(int arr[][n] , int r , int c) {
int co = 0;
for (int i = 0 ; i < n ; ++i)
if (safe(arr , r + x_move[i] , c + y_move[i]))
c++;
return c;
}
bool next_one(int arr[][n] , int *r , int *c) {
int nr , nc;
int min_dep_index = -1;
int min_dep = n + 1;
int k;
int s = rand() % n;
for (int co = 0 ; co < n ; ++co) {
int i = (s + co) % n;
nr = *r + x_move[i];
nc = *c + y_move[i];
k = depth(arr , nr , nc);
if (safe(arr , *r , *c) && k < min_dep) {
min_dep_index = i;
min_dep = k;
}
}
if (min_dep_index == -1)
return false;
nr = *r + x_move[min_dep_index];
nc = *c + y_move[min_dep_index];
arr[nr][nc] = arr[*r][*c] + 1;
*r = nr;
*c = nc;
return true;
}
bool foo(int arr[][n]) {
for (int i = 0 ; i < n ; ++i)
for (int j = 0 ; j < n ; ++j)
arr[i][j] = -1;
int r , c , sr , sc;
sc = rand() % n;
sr = rand() % n;
r = sr;
c = sc;
arr[r][c] = 1;
for (int i = 0 ; i < n*n ; ++i) {
if (next_one(arr , &r , &c) == false)
return false;
}
if (!neighbour(r , c , sr , sc))
return false;
print(arr);
return true;
}
int main() {
int arr[n][n];
srand(time(nullptr));
while (foo(arr) == false) {
;
}
return 0;
}