How do you find the location of a number in a sequence? - c++

Say that I have a sequence:
int seq[4][4];
Then, lets say seq[1][2]=8;
No other values of the sequence yields 8.
If I want to find the values of a sequence and print out which one it is, (e.g. 1,2 and make x=1 and y=2) how can I do that? What

int x,j;
for (int i = 0; i < 4; i++) // looping through row
{
for(int j = 0; j < 4; j++) //looping through column
{
if (seq[i][j] == 8) //if value matches
{
x = i; y = j; //set value
i = 4; //set i to 4 to exit outer for loop
break; //exit inner for loop
}
}
}

int numberBeingSearchedFor = *Any Value Here*;
int array[*numRows*][*numColumns*];
int firstOccuranceRow = -1, firstOccuranceColumn = -1;
for(int i = 0; i < numRows; ++i)
{
for(int j = 0; j < numColumns; ++j)
{
if(array[i][j] == numberBeingSearchedFor)
{
firstOccuranceRow = i;
firstOccuranceColumn = j;
i = numRows; //Credit to other answer, I've never seen that :) It's cool
break;
}
}
}
if(firstOccuranceRow == -1 || firstOccuranceColumn == -1)
{
//Item was not in the array
}

Related

MAX_value in 2d array for each column

What is wrong with that code?
Sorry, if here bad code.
I'm need to find max value for all column in 2d dimensional of float values, then find them sum.
First of all I write values for Array, then display them at screen and tried to find max values for each column.
Photo: didn't working and correctly work
___________________
[5.7 ; 4.2 ; 5.8;]
[654.87; 5.86; 3.76;] - Work correctly
[8.54; 7.54; 8.4;]
------------------
Max value of 1 column = A[2,1] = 654.87;
Max value of 2 column = A[3,2] = 7.54;
Max value of 3 column = A[3,3] = 8.4;
___________________
[4.6 ; 2.65 ; 76.3;]
[65.64; 7.32; 76.2;] - Work not correctly
[654.8; 1.6; 5.7;]
------------------
Max value of 1 column = A[3,1] = 654.8;
Max value of 2 column = A[3,2] = 7.32;
Max value of 3 column = A[3,3] = 5.7;
#include<iostream>
#include<conio.h>
int main(void)
{
system("cls");
int N;
int suma = 0;
A:
std::cout<<"Write array size N x N : ";
std::cin>>N;
if(N>10 || N<=1)
{
system("cls");
std::cout<<"N must be <= 10 and > 1;"<<std::endl;
goto A;
}
float **A = new float *[N];
for(int i = 0; i < N; i++)
{
A[i] = new float [N];
for(int j = 0; j < N; j++)
{
std::cout<<"A["<<i+1<<"][";
std::cout<<j+1<<"] = ";
std::cin>>(*(*(A+i)+j));
}
}
system("cls");
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if(j<N-1)
{
std::cout<<"A["<<i+1<<"]["<<j+1<<"] = "<<*(*(A+i)+j);
std::cout<<"; ";
}
else
{
std::cout<<"A["<<i+1<<"]["<<j+1<<"] = "<<*(*(A+i)+j);
std::cout<<";"<<std::endl;
}
}
}
float *max = new float [N];
std::cout<<"------------------------------------";
std::cout<<std::endl;
for(int i = 0; i < N - (N - 1); i++)
{
for(int j = 0; j < N; j++)
{
*(max+j) = *(*(A+i)+j);
}
}
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if( (*(max+i)) < (*(*(A+j))+i) &&
(*(max+i)) != ((*(*(A+j)))+i) )
{
*(max+i) = *(*(A+j)+i);
}
}
}
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if( (*(*(A+j)+i)) == (*(max+i)) )
{
std::cout<<"Max value of "<<i+1;
std::cout<<" column = ";
std::cout<<"A["<<j+1<<"]["<<i+1;
std::cout<<"] = "<<(*(max+i));
std::cout<<std::endl;
}
}
suma+=(*(max+i));
}
std::cout<<"Sum of largest value = "<<suma;
_getch();
}
Oh... sorry just a mistake in if() by which i losen more than 3.5 hour...
if( (*(max+i)) < (*(*(A+j))+i)
&&
(*(max+i)) != ((*(*(A+j)))+i) )
{...}
I changed it to:
if( (*(max + i)) < (*(*(A + j) + i))
&&
(*(max + i)) != (*(*(A + j) + i))
)
{...}
After that change all work properly

how to fill array with contents of another array that has different size using loops

I am trying to fill an array sized by [4344][20] with the contents of other array sized by [5430][20]. I wrote the following code and it has no errors. It filled the X_train correctly, but the Y_train didn't filled successfully. it remained zeros as its initialized.
my code:
void split(int fold, int array_X_set[5430][20], int array_Y_set[5430],
int X_train[4344][20], int Y_train[4344],
int X_test[1086][20], int Y_test[1086])
{
int rows = 5430;
int cols = 20;
int division = 1086;
int nTest = 0, nTrain = 0, nTest1 = 0, nTrain1 = 0;
switch (fold) {
case 1:
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (i < division) {
X_test[nTest][nTest1] = array_X_set[i][j];
Y_test[nTest] = array_Y_set[i];
nTest1++;
}
else {
X_train[nTrain][nTrain1] = array_X_set[i][j];
Y_train[nTrain] = array_Y_set[i];
nTrain1++;
}
}
}
break;
another condition :
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (i >= 1086 && i <= 2171) {
X_test[i][j] = array_X_set[i][j];
Y_test[i] = array_Y_set[i];
}
else {
X_train[i - division][j] = array_X_set[i][j];
Y_train[i - division] = array_Y_set[i];
}
}
}
you can try this code, so that you don't need extra variable like nTest, nTrain, nTest1, nTrain1.
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (i < division) {
X_test[i][j] = array_X_set[i][j];
Y_test[i] = array_Y_set[i];
} else {
X_train[i-division][j] = array_X_set[i][j];
Y_train[i-division] = array_Y_set[i];
}
}
}
updated:
Another condition:
if you have 10 elements in array
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
^ ^ ^ ^
you want to put index 3~6 to new array, in new array, its index would be 0~3
so for the part >=3 && <=6 would be newArr[i-3] = originalArr[i]
and if you want to put index 0~2 and 7~9 to new array, in new array, its index would be 0~2 and 3~5
so for the part <3 would be newArr[i] = originalArr[i]
the part >6 would be newArr[i-(6-3+1)] = originalArr[i], (6-3+1) means the element count between the part >=3 && <=6
Here is the code in your condition:
(>=1086 && <=2171 in test array, <1086 || >2172 in train array)
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (i >= 1086 && i <= 2171) {
X_test[i - 1086][j] = array_X_set[i][j];
Y_test[i - 1086] = array_Y_set[i];
}
else {
if(i<1086){
X_train[i][j] = array_X_set[i][j];
Y_train[i] = array_Y_set[i];
}else{
X_train[i - (2171-1086+1)][j] = array_X_set[i][j];
Y_train[i - (2171-1086+1)] = array_Y_set[i];
}
}
}
}

nqueens - checking with the board, instead of previous queens

There are so many questions regarding Nqueens problem here. However, my implementation is different. My code checks with the board if queen placement is possible, instead of checking with the position of the previous queen.
It goes like this:
initially, the board has all zeros filled. The algorithm starts with the position (0,0). Then, it checks
row-wise per column to find the first 0. After finding the first zero, it changes the zero to one.
From this point onward, my logic differs. Instead of going to the next column, it first disables all the
positions, which the currently placed queen attacks, i.e. writes -1 on those places, i.e., row, column,
upper diagonal and lower diagonal. Now, the column value increments, and instead of check with the previous queen,
it simply has to find the first zero. Then again, relative positions get disabled.... you get the idea.
The code:
#include <iostream>
int board[8][8];
void printBoard() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
std::cout << board[i][j] << " ";
}
std::cout << "\n";
}
}
void disablePositions(int row, int col) {
//disable row
for (int j = col + 1; j < 8; j++) {
board[row][j] = 2;
}
//disable column
for (int i = 0; i < 8; i++) {
if (board[i][col] == 1) {
continue;
}
board[i][col] = 2;
}
//disable upper diagonal
for (int i = row - 1, j = col + 1; i >= 0 || j < 8; i--, j++) {
board[i][j] = 2;
}
for (int i = row + 1, j = col + 1; i < 8 || j < 8; i++, j++) {
board[i][j] = 2;
}
}
void solve(int initial_row) {
int init = initial_row;
int row = 0;
int col = 0;
while (col != 8) {
for (row = init; row < 8; row++) {
if (board[row][col] == 0) {
board[row][col] = 1;
break;
}
}
if (row == 8) {
col = 0;
initial_row++;
init = initial_row;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
board[i][j] = 0;
}
}
}
else {
init = 0;
disablePositions(row, col);
col++;
}
printBoard();
std::cout << std::endl;
}
}
int main() {
solve(0);
std::cout << std::endl;
}
This code is for 8-queens. The problem is, after it reaches the stage where it starts from [5][0], it just crashes. What is causing the issue?
Also, as it tries to make an optimal choice at every stage, would we call it greedy algorithm?
In your disable upper diagonal loops, you have the condition wrong. Using an || operation, the looping continues when either condition is true, which will lead to out-of-bounds access to the array.
Change the conditions in both for loops to be && (and).

Null characters randomly added to string C++

I have written a simple battleship game in C++. After several iterations of the game, one of the strings in a "Player" object is changed. This change is several null characters are added to the end of the string. Otherwise the rest of the object is untouched. For example if the player type is "cpu", the player type switches to "cpu\0\0\0\0\0\0\0\0". I believe the line of code causing the problem is:
currPlayer->getStrategy().getNextAttack(nextPlayer->getBoard(1));
Here is the code for getNextAttack():
int Strategy::getNextAttack(Board enemyBoard) {
//clear prob board
for(int i = 0; i < 100; i++) {
probBoard[i] = 0;
}
//reset largest ship
largestShip = 0;
//assign largest ship
for(int i = 0; i < 100; i++) {
Ship currShip = enemyBoard.getShipByCoord(i);
if(!currShip.isSunk()) { //if ship is still afloat
if(currShip.getSize() > largestShip) { largestShip = currShip.getSize(); } //reassign largest ship on board
}
}
//assign base prob
std::vector<int> allPossible;
//for all horiz coords
for(int i = 0; i < 10; i++) {
for(int j = 0; j < (10 - largestShip +1); j++) {
for(int k = 0; k < (largestShip); k++) {
if(!enemyBoard.beenHit((i*10) + j + k) || (enemyBoard.beenHit((i*10) + j + k) && !enemyBoard.getShipByCoord((i*10) + j + k).isSunk())) { //if not hit or if hit but contains a ship that is not sunk
allPossible.push_back((i*10) + j + k);
}
else {
for(int m = 0; m < k; m++) {
allPossible.pop_back(); //should delete last element
}
break;
}
}
//for all vert coords
for(int z = 0; z < (largestShip); z++) {
if(!enemyBoard.beenHit(((j+z)*10) + i)) {
allPossible.push_back(((j+z)*10) + i);
}
else {
for(int m = 0; m < z; m++) {
allPossible.pop_back(); //should delete last element
}
break;
}
}
}
}
for(int p = 0; p < allPossible.size(); p++) {
probBoard[allPossible[p]] += 1;
}
//add improvements based on hits
for(int i = 0; i < 10; i++) {
for(int k = 0; k < 10; k++) {
int currCoord = (i*10) + k;
int leftCoord = (i*10) + k-1;
int rightCoord = (i*10) + k+1;
int upCoord = ((i-1)*10) + k;
int downCoord = ((i+1)*10) + k;
if(enemyBoard.beenHit(currCoord) && (enemyBoard.getShipByCoord(currCoord).getName() != "") && !enemyBoard.getShipByCoord(currCoord).isSunk()) { //currCoord is a coordinate that has been hit, contains a ship and is not sunk
if((enemyBoard.beenHit(leftCoord) || enemyBoard.beenHit(rightCoord)) && (enemyBoard.getShipByCoord(leftCoord) == enemyBoard.getShipByCoord(currCoord) || enemyBoard.getShipByCoord(rightCoord) == enemyBoard.getShipByCoord(currCoord))) { //if space to left or right is hit and the same ship
//increment only the left and right
if(!enemyBoard.getShipByCoord(currCoord).isSunk()) { //ship cannot be sunk as well
probBoard[leftCoord] += 25;
probBoard[rightCoord] += 25;
}
}
else if((enemyBoard.beenHit(upCoord) || enemyBoard.beenHit(downCoord)) && (enemyBoard.getShipByCoord(upCoord) == enemyBoard.getShipByCoord(currCoord) || enemyBoard.getShipByCoord(downCoord) == enemyBoard.getShipByCoord(currCoord))) { //if space on top or bottom is hit and the same ship and not sunk
//increment only the top and bottom
if(!enemyBoard.getShipByCoord(currCoord).isSunk()) { //ship cannot be sunk as well
probBoard[upCoord] += 25;
probBoard[downCoord] += 25;
}
}
//if no direct spaces in any direction to hit coord, increment top, bot, left, and right equally
else {
probBoard[upCoord] += 20;
probBoard[downCoord] += 20;
probBoard[leftCoord] += 20;
probBoard[rightCoord] += 20;
}
}
}
}
//marks odds at 0 if already fired upon
for(int n = 0; n < 100; n++) {
if(enemyBoard.beenHit(n)) {
probBoard[n] = 0;
}
}
//find next best attack coord based on prob board
int highestValue = 0;
std::vector<int> highestSpaces;
for(int j = 0; j < 100; j++) {
if(probBoard[j] > highestValue) { highestValue = probBoard[j]; }
}
for(int r = 0; r < 100; r++) {
if(probBoard[r] == highestValue) {
highestSpaces.push_back(r);
}
}
srand(static_cast<unsigned int>(time(NULL)));
int randNum = rand() % highestSpaces.size();
return highestSpaces[randNum];
}
Thank you for reading and any help!
This looks like it will go out of the array bounds at the edges when the row or column is 0 or 9:
probBoard[upCoord] += 20;
probBoard[downCoord] += 20;
probBoard[leftCoord] += 20;
probBoard[rightCoord] += 20;

Puzzle related to sorting a 2-D array in ascending order

A randomly generated 4x4 2-D array is given to the user, of which one element is definitely 0. Considering 0 to be an empty location, the user will have to exchange the remaining 15 elements with 0 repeatedly until they get the array in ascending order, with 0 as the last element.
At this point, they're allowed to exchange any element with 0.
But how do I modify this code to ensure that are only able to exchange those elements with 0 that are adjacent to it (either above, below or beside it) ?
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
int check_asc(int a[][4])
{
int i, j, previous = a[0][0];
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
if(i == 3 && j == 3)
{
if (a[i][j] == 0)
return 1;
}
else if (a[i][j] < previous)
{
return 0;
}
previous = a[i][j];
}
}
return 1;
}
void swap(int a[][4], int &xpos, int &ypos)
{
int arr, temp;
cout << "\n\nEnter number to be swapped with 0: ";
cin >> arr;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (a[i][j] == arr)
{
temp = a[xpos][ypos];
a[xpos][ypos] = a[i][j];
a[i][j] = temp;
xpos = i;
ypos = j;
return;
}
}
}
}
int check_rep(int a[][4], int assign)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (assign == a[i][j])
return 0;
}
}
return 1;
}
void main()
{
int a[4][4], assign, xpos = 0, ypos = 0, asc_result, rep_result;
srand((unsigned)time(NULL));
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
{
if (i == 0 && j == 0)
a[i][j] = 0;
else
{
do {
assign = rand() % 50;
rep_result = check_rep(a, assign);
} while (rep_result == 0);
a[i][j] = assign;
}
}
cout << "\n\nArrange the 4x4 matrix into ascending order. (Consider 0 as a blank space)" << endl;
for (int i = 0; i < 4; i++)
{
cout << endl;
for (int j = 0; j < 4; j++)
cout << a[i][j] << '\t';
}
do {
swap(a, xpos, ypos);
system("cls");
for (int i = 0; i < 4; i++)
{
cout << endl;
for (int j = 0; j < 4; j++)
cout << a[i][j] << '\t';
}
asc_result = check_asc(a);
} while (asc_result == 0);
cout << "\n\tYou win"<<endl;
system("pause");
}
Simple, just extend your swap function with a piece of code that will check whether the location of the element to be swapped is adjacent to the location of 0:
void swap(int a[][4], int &xpos, int &ypos)
{
...
if (a[i][j] == arr &&
((i == xpos && (j == ypos - 1 || j == ypos + 1)) ||
(j == ypos && (i == xpos - 1 || i == xpos + 1))))
{
temp = a[xpos][ypos];
a[xpos][ypos] = a[i][j];
a[i][j] = temp;
xpos = i;
ypos = j;
return;
}
An improvement would be to separate the check condition and inform the user in case when the element is not adjacent to 0.
Rough Algorithm
1) create a function find location, it will return a structure Point that has x, y integer fields, it will find the x, y location of any piece based on the pieces value, i.e. lets say 0 is entered, if it is located in the top left corner (0,0), a point (0, 0) will be returned
2) create a function that takes in 2 points, the location of the '0' and the location of the piece we wish to swap lets call it S, if S.x = 0.x and 0.y - 1 = S.y or S.y - 0.y + 1 then you know that said piece is directly above or below the 0, now of course you have ot add a few conditions for boundaries so as we dont check outside the grid. Have this function return an int 1 if the piece S is located above/below/beside, 0 if not.
3) if 1 is returned your allowed to do the flip, if 0 is returned find another piece