Trim Image White Space with maintaining the Aspect ratio - wpf

i am trying to trim and crop image without the whitespace surrounded with , but the image i got has aspect ratio not equal to the original image .
i am using the following code in C#
public Bitmap TrimImageWhiteSpaces(Bitmap bitmap)
{
int w = bitmap.Width;
int h = bitmap.Height;
Func<int, bool> isAllWhiteRow = row =>
{
for (int i = 0; i < w; i++)
{
if (bitmap.GetPixel(i, row).R != 255)
{
return false;
}
}
return true;
};
Func<int, bool> isAllWhiteColumn = col =>
{
for (int i = 0; i < h; i++)
{
if (bitmap.GetPixel(col, i).R != 255)
{
return false;
}
}
return true;
};
int leftMost = 0;
for (int col = 0; col < w; col++)
{
if (isAllWhiteColumn(col)) leftMost = col + 1;
else break;
}
int rightMost = w - 1;
for (int col = rightMost; col > 0; col--)
{
if (isAllWhiteColumn(col)) rightMost = col - 1;
else break;
}
int topMost = 0;
for (int row = 0; row < h; row++)
{
if (isAllWhiteRow(row)) topMost = row + 1;
else break;
}
int bottomMost = h - 1;
for (int row = bottomMost; row > 0; row--)
{
if (isAllWhiteRow(row)) bottomMost = row - 1;
else break;
}
if (rightMost == 0 && bottomMost == 0 && leftMost == w && topMost == h)
{
return bitmap;
}
int croppedWidth = rightMost - leftMost + 1;
int croppedHeight = bottomMost - topMost + 1;
try
{
Bitmap target = new Bitmap(croppedWidth, croppedHeight);
using (Graphics g = Graphics.FromImage(target))
{
g.DrawImage(bitmap,
new RectangleF(0, 0, croppedWidth, croppedHeight),
new RectangleF(leftMost, topMost, croppedWidth, croppedHeight),
GraphicsUnit.Pixel);
}
//target = (Bitmap)FixedSize(target,bitmap.Height, bitmap.Width,false);
return target;
}
catch (Exception ex)
{
throw new Exception($"Values are top={topMost} bottom={bottomMost} left={leftMost} right={rightMost}", ex);
}
}
this is the original image
and this the image i got after executing the code
So Please is there any way to trim the image with preserving the aspect ratio of the original image

Related

Connect-N game in C check for wins functions not working

I'm trying to write a program to play the game Connect-N, which is basically Connect-4 but the user determines the size of the board (it is not necessarily square) and the number of consecutive pieces to win (which can be greater than the size of the board - if the board is 3x3, the user could specify that you need 4 pieces to win, and my code has to play out the game to a tie since it's impossible to win). I'm checking for 4 cases: horizontal win, vertical win, left diagonal win, and right diagonal win. I wrote out the logical steps to actually check for the wins, and then tried to turn that into code. However, when I run the actual program, it keeps returning that it's a tie game even when a player has won, which can only be reached if all 4 win functions return false. Can anyone spot the error in my code?
Here is my code:
(just for reference, the variable pieces represents either an X or O)
Horizontal win:
bool horizontalWin(char **board, const int numRows, const int numCols, const char blankSpace, const int numToWin, const char pieces) {
int match = 0;
if (numCols < numToWin) {
return false;
}
else {
for (int row = 0; row < numRows; ++row) {
for (int col = 0; col <= numCols - numToWin; ++col) {
for (int k = 0; k < numToWin; ++k) {
if (board[row][col + k] != pieces) {
match = 0;
}
else {
++match;
if (match == numToWin) {
return true;
}
}
}
}
}
}
return false;
}
Vertical win:
bool verticalWin(char **board, const int numRows, const int numCols, const char blankSpace, const int numToWin, const char pieces) {
int match = 0;
if (numRows < numToWin) {
return false;
}
else {
for (int col = 0; col < numCols; ++col) {
for (int row = 0; row <= numRows - numToWin; ++row) {
for(int k = 0; k < numToWin; ++k){
if (board[row + k][col] != pieces) {
match = 0;
}
else {
++match;
if (match == numToWin) {
return true;
}
}
}
}
}
}
return false;
}
Left diagonal:
bool leftDiagonalWin(char **board, const int numRows, const int numCols, const char blankSpace, const int numToWin, const char pieces) {
int match = 0;
if (numCols < numToWin || numRows < numToWin) {
return false;
}
else {
for (int row = 0; row <= numRows - numToWin; ++row) {
for (int col = 0; col <= numCols - numToWin; ++col) {
for (int k = 0; k < numToWin; ++k) {
if(board[k][k] != pieces) {
match = 0;
}
else {
++match;
if (match == numToWin) {
return true;
}
}
}
}
}
}
return false;
}
Right diagonal:
bool rightDiagonalWin(char **board, const int numRows, const int numCols, const char blankSpace, const int numToWin, const char pieces) {
int match = 0;
if (numCols < numToWin || numRows < numToWin) {
return false;
}
else {
for (int row = numRows - 1; row >= numRows - numToWin; --row) {
for (int col = 0; col <= numCols - numToWin; ++col) {
for (int k = 0; k < numToWin; ++k) {
if (board[numRows - 1 - k][col + k] != pieces) {
match = 0;
} else {
++match;
if (match == numToWin) {
return true;
}
}
}
}
}
}
return false;
}
Edit: this is the function I use to create the board:
char** createBoard(const int numRows, const int numCols, const char blankSpace) {
char** board = (char**) malloc(numRows * sizeof(char*));
for (int row = 0; row < numRows; ++row) {
board[row] = (char*) malloc(numCols * sizeof(char));
for (int col = 0; col < numCols; ++col) {
board[row][col] = blankSpace;
}
}
return board;
}
Your horizontal solution is way too complicated. The "blankSpace" parameter is not even used or needed. Here's a much, much simplified version:
bool horizontalWin(char **board, const int numRows, const int numCols,
const int numToWin, const char piece) {
int match = 0;
for (int row = 0; row < numRows; ++row) {
for (int col = 0; col <= numCols; ++col) {
match = (board[row][col] == piece) ? (match + 1) : 0;
if (match == numToWin) {
break;
}
}
}
return (match >= numToWin);
}
You can pretty much duplicate this same logic for the verticalWin function as well.
I know this is late:( but this is how I went about it hope it helps
//check win
int checkWin(char *board){
return (horizontalCheck(board) || verticalCheck(board) || diagonalCheck(board));
}
int checkFour(char *board, int a, int b, int c, int d){
//board[a] = won;
//board[b] = won;
//board[c] = won;
//board[d] = won;
return (board[a] == board[b] && board[b] == board[c] && board[c] == board[d] && board[a] != ' ');
}
int horizontalCheck(char *board){
int row, col, idx;
const int WIDTH = 1;
for(row = 0; row < BOARD_ROWS; row++){
for(col = 0; col < BOARD_COLS - 3; col++){
idx = BOARD_COLS * row + col;
if(checkFour(board, idx, idx + WIDTH, idx + WIDTH * 2, idx + WIDTH * 3)){
return 1;
}
}
}
return 0;
}
int verticalCheck(char *board){
int row, col, idx;
const int HEIGHT = 7;
for(row = 0; row < BOARD_ROWS - 3; row++){
for(col = 0; col < BOARD_COLS; col++){
idx = BOARD_COLS * row + col;
if(checkFour(board, idx, idx + HEIGHT, idx + HEIGHT * 2, idx + HEIGHT * 3)){
return 1;
}
}
}
return 0;
}
//diagonal check for win
int diagonalCheck(char *board){
int row, col, idx, count = 0;
const int DIAG_RGT = 6, DIAG_LFT = 8;
for(row = 0; row < BOARD_ROWS - 3; row++){
for(col = 0; col < BOARD_COLS; col++){
idx = BOARD_COLS * row + col;
if(((count <= 3) && (checkFour(board, idx, idx + DIAG_LFT, idx + DIAG_LFT * 2, idx + DIAG_LFT * 3))) ||
((count >= 3) && (checkFour(board, idx, idx + DIAG_RGT, idx + DIAG_RGT * 2, idx + DIAG_RGT * 3)))){
return 1;
}
count++;
}
count = 0;
}
return 0;
}

c sudoku solver with recursive backtracking returning errors [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hey everyone so I wrote a sudoku solver in C that uses recursive backtracking. However the output is not what's expected.For the code to work you need to pass in an array of 81 numbers, and the 0 on the board equals a '.' in the array. The problem is that my output starts filling in everything with 1's in place of where the '.'. I dont understand why and I need a fresh pair of eyes to look it over for me.
#define DEBUG FALSE
#define TRUE 1
#define FALSE 0
#include <stdio.h>
/* function declarations */
int readPuzzle(int puzzle[9][9]);
int findRowErrors(int puzzle[9][9]);
int findColErrors(int puzzle[9][9]);
int findBoxErrors(int puzzle[9][9]);
int solvePuzzle(int puzzle[9][9], int index);
int validMove(int puzzle[9][9], int index, int num);
int noSolution(int puzzle[9][9]);
void writePuzzle(int puzzle[9][9]);
int main (void)
{
int puzzle[9][9];
int index = 0;
int error;
while ((error = readPuzzle(puzzle)) != EOF)
{
error += findRowErrors(puzzle);
error += findColErrors(puzzle);
error += findBoxErrors(puzzle);
if (error) printf("Error\n\n");
else
{
/* in DEBUG mode, show initial puzzle in standard sudoku form */
if (DEBUG) writePuzzle(puzzle);
solvePuzzle(puzzle, index);
if (!noSolution(puzzle)) writePuzzle(puzzle);
}
}
return 0;
}
int readPuzzle(int puzzle[9][9])
{
int i, num, row, col;
int error = FALSE;
for (i = 0; (num = getchar()) != '\n'; i++)
{
if (num == EOF) return EOF;
putchar(num);
if ((num < '1' || num > '9') && (num != '.')) error = TRUE;
if (num == '.') num = '0';
row = (i / 9) % 9;
col = i % 9;
puzzle[row][col] = num - '0';
}
putchar('\n');
if (i != 81) error = TRUE;
return error;
}
int findRowErrors(int puzzle[9][9])
{
int row, col, i;
/* check rows */
for (row = 0; row < 9; row++)
{
for (col = 0; col < 9; col++)
{
for (i = col + 1; i < 9; i++)
{
if ( (puzzle[row][col] != 0) && (puzzle[row][col] == puzzle[row][i]) )
{
return TRUE; /* row error found in puzzle\
*/
}
}
}
}
return FALSE;
}
int findColErrors(int puzzle[9][9])
{
int row, col, i;
for (col = 0; col < 9; col++)
{
for (row = 0; row < 9; row++)
{
for (i = row + 1; i < 9; i++)
{
if ( (puzzle[row][col] != 0) && (puzzle[row][col] == puzzle[i][col]) )
{
return TRUE; /* column error found in puzzle */
}
}
}
}
return FALSE;
}
int findBoxErrors(int puzzle[9][9])
{
int row, col, i, j;
for (row = 0; row < 9; row += 3)
{
for (col = 0; col < 9; col += 3)
{
for (i = 0; i < 9; i++)
{
for (j = i + 1; j < 9; j++)
{
if ( (puzzle[row + i / 3][col + i % 3] != 0) &&
(puzzle[row + i / 3][col + i % 3] ==
puzzle[row + j / 3][col + j % 3]) )
{
return TRUE; /* box error found in puzzle*/
}
}
}
}
}
return FALSE;
}
int noSolution(int puzzle[9][9])
{
int row, col;
for (row = 0; row < 9; row++)
{
for (col = 0; col < 9; col++)
{
if (!puzzle[row][col])
{
printf("No solution\n\n");
return TRUE;
}
}
}
return FALSE;
}
void writePuzzle(int puzzle[9][9])
{
int row, col;
for (row = 0; row < 9; row++)
{
if (DEBUG) printf("\n");
if ((DEBUG) && (row == 3 || row == 6))
{
printf("----------------------\n");
}
for (col = 0; col < 9; col++)
{
if (DEBUG) printf(" ");
if (puzzle[row][col]) printf("%d", puzzle[row][col]);
else printf(".");
if ((DEBUG) && (col == 2 || col == 5)) printf(" |");
}
}
printf("\n\n");
}
int solvePuzzle(int puzzle[9][9], int index)
{
int num;
int row = index / 9;
int col = index % 9;
if (index == 81) return TRUE; /* all cells are filled */
if (puzzle[row][col] != 0)
{
return solvePuzzle(puzzle, ++index); /* recursive call */
}
else
{
for (num = 1; num <= 9; num++)
{
if (validMove(puzzle, index, num))
{
puzzle[row][col] = num;
if (solvePuzzle(puzzle, index)) return TRUE;
puzzle[row][col] = 0;
}
}
return FALSE;
}
}
/*Checks to see Valid moves for rows, columns, and regions*/
int validMove(int puzzle[9][9],int start, int num)
{
int r, c;
int row = start / 9;
int column = start % 9;
int regionFirstRow = row - (row %3 );
int regionFirstColumn = column - (row % 3);
/*Checks rows for valid moves*/
for(c = 0; c < 9; c++)
{
if(puzzle[row][c] == num)
{
return FALSE;
}
}
/*Checks columns for valid moves*/
for(r = 0; r < 9; r++)
{
if(puzzle[r][column] == num)
{
return FALSE;
}
}
/*FINISH THIS!!!!!!!!!*/
/*Checks each 3x3 region for valid moves*/
for(r = 0; r < 3; r++)
{
for(c = 0; c < 3; c++)
{
if(puzzle[regionFirstRow + r][regionFirstColumn + c] == num)
{
return FALSE;
}
}
}
return TRUE;
}
}
There is a bug in the box region calculation in function validMove
int regionFirstColumn = column - (row % 3);
should be
int regionFirstColumn = column - (column % 3);

Cell Compete Problems

Here is my assignment:
There is a colony of 8 cells arranged in a straight line where each day every cell competes with its adjacent cells(neighbour). Each day, for each cell, if its neighbours are both active or both inactive, the cell becomes inactive the next day,. otherwise itbecomes active the next day.
Assumptions: The two cells on the ends have single adjacent cell, so
the other adjacent cell can be assumsed to be always inactive. Even
after updating the cell state. consider its pervious state for
updating the state of other cells. Update the cell informationof
allcells simultaneously.
Write a fuction cellCompete which takes takes one 8 element array of
integers cells representing the current state of 8 cells and one
integer days representing te number of days to simulate. An integer
value of 1 represents an active cell and value of 0 represents an
inactive cell.
Program:
int* cellCompete(int* cells,int days)
{
//write your code here
}
//function signature ends
Test Case 1:
INPUT:
[1,0,0,0,0,1,0,0],1
EXPECTED RETURN VALUE:
[0,1,0,0,1,0,1,0]
Test Case 2:
INPUT:
[1,1,1,0,1,1,1,1,],2
EXPECTED RETURN VALUE:
[0,0,0,0,0,1,1,0]
This is the problem statement given above for the problem. The code which I have written for this problem is given below. But the output is coming same as the input.
#include<iostream>
using namespace std;
// signature function to solve the problem
int *cells(int *cells,int days)
{ int previous=0;
for(int i=0;i<days;i++)
{
if(i==0)
{
if(cells[i+1]==0)
{
previous=cells[i];
cells[i]=0;
}
else
{
cells[i]=0;
}
if(i==days-1)
{
if(cells[days-2]==0)
{
previous=cells[days-1];
cells[days-1]=0;
}
else
{
cells[days-1]=1;
}
}
if(previous==cells[i+1])
{
previous=cells[i];
cells[i]=0;
}
else
{
previous=cells[i];
cells[i]=1;
}
}
}
return cells;
}
int main()
{
int array[]={1,0,0,0,0,1,0,0};
int *result=cells(array,8);
for(int i=0;i<8;i++)
cout<<result[i];
}
I am not able to get the error and I think my logic is wrong. Can we apply dynamic programming here If we can then how?
private List<Integer> finalStates = new ArrayList<>();
public static void main(String[] args) {
// int arr[] = { 1, 0, 0, 0, 0, 1, 0, 0 };
// int days = 1;
EightHousePuzzle eightHousePuzzle = new EightHousePuzzle();
int arr[] = { 1, 1, 1, 0, 1, 1, 1, 1 };
int days = 2;
eightHousePuzzle.cellCompete(arr, days);
}
public List<Integer> cellCompete(int[] states, int days) {
List<Integer> currentCellStates = Arrays.stream(states).boxed().collect(Collectors.toList());
return getCellStateAfterNDays(currentCellStates, days);
}
private List<Integer> getCellStateAfterNDays(List<Integer> currentCellStates, int days) {
List<Integer> changedCellStates = new ArrayList<>();
int stateUnoccupied = 0;
if (days != 0) {
for (int i1 = 0; i1 < currentCellStates.size(); i1++) {
if (i1 == 0) {
changedCellStates.add(calculateCellState(stateUnoccupied, currentCellStates.get(i1 + 1)));
} else if (i1 == 7) {
changedCellStates.add(calculateCellState(currentCellStates.get(i1 - 1), stateUnoccupied));
} else {
changedCellStates
.add(calculateCellState(currentCellStates.get(i1 - 1), currentCellStates.get(i1 + 1)));
}
}
if (days == 1) {
System.out.println("days ==1 hit");
finalStates = new ArrayList<>(changedCellStates);
return finalStates;
}
days = days - 1;
System.out.println("Starting recurssion");
getCellStateAfterNDays(changedCellStates, days);
}
return finalStates;
}
private int calculateCellState(int previousLeft, int previousRight) {
if ((previousLeft == 0 && previousRight == 0) || (previousLeft == 1 && previousRight == 1)) {
// the state gets now changed to 0
return 0;
}
// the state gets now changed to 0
return 1;
}
Here is my solution in Java:
public class Colony
{
public static int[] cellCompete(int[] cells, int days)
{
int oldCell[]=new int[cells.length];
for (Integer i = 0; i < cells.length ; i++ ){
oldCell[i] = cells[i];
}
for (Integer k = 0; k < days ; k++ ){
for (Integer j = 1; j < oldCell.length - 1 ; j++ ){
if ((oldCell[j-1] == 1 && oldCell[j+1] == 1) || (oldCell[j-1] == 0 && oldCell[j+1] == 0)){
cells[j] = 0;
} else{
cells[j] = 1;
}
}
if (oldCell[1] == 0){
cells[0] = 0;
} else{
cells[0] = 1;
}
if (oldCell[6] == 0){
cells[7] = 0;
} else{
cells[7] = 1;
}
for (Integer i = 0; i < cells.length ; i++ ){
oldCell[i] = cells[i];
}
}
return cells;
}
}
Your program does not distinguish between the number of days to simulate and the number of cells.
#include <bits/stdc++.h>
using namespace std;
int* cellCompete(int* cells,int days)
{
for(int j=0; j<days; j++)
{
int copy_cells[10];
for(int i=1; i<9; i++)
copy_cells[i]=cells[i-1];
copy_cells[0]=0;copy_cells[9]=0;
for(int i=0; i<8; i++)
cells[i]=copy_cells[i]==copy_cells[i+2]?0:1;
}
return cells;
}
int main()
{
int arr[8]={1,1,1,0,1,1,1,1};
int arr2[8]={1,0,0,0,0,1,0,0};
cellCompete(arr2,1);
for(int i=0; i<8; i++)
{
cout<<arr2[i]<<" ";
}
}
Here's some sweet little python code:
def cell(arr, days):
new = arr[:] #get a copy of the array
n = len(arr)
if n == 1: print [0] #when only 1 node, return [0]
for _ in range(days):
new[0] = arr[1] #determine the edge nodes first
new[n - 1] = arr[n - 2]
for i in range(1, n-1):
new[i] = 1 - (arr[i-1] == arr[i+1]) #logic for the rest nodes
arr = new[:] #update the list for the next day
return new
arr = [1, 1, 1, 0, 1, 1, 1, 1]
days = 2
print cell(arr, days)
You can easily do this in Javascript with few lines of code
let cells = [1,1,1,0,1,1,1,1];
let numOfDays = 2;
let changeState = (cellarr)=> cellarr.map((cur, idx, arr)=> (arr[idx-1] ||0) + (arr[idx+1] || 0)===1?1:0);
let newCells =cells;
for (let i = 0 ; i <numOfDays; i++) newCells = changeState(newCells);
console.log(newCells);
This is a C# version of a possible answer. I really struggled with this for a while for some reason!
I also incorporated some of Janardan's stuff above as it helped spur me in the right direction. (cheers!)
The tricky part of the question was dealing with the fact that you had to persist the state of the cell to figure out the next cell competition which I had originally tried with a second array which was messy.
Note: I chose to use the Array.Copy method as I believe it is slightly more efficient and a lot more readable than copying arrays with a for loop when reading through.
Hopefully this helps someone out in the future!
public int[] cellCompete(int[] cell, int day)
{
//First create an array with an extra 2 cells (these represent the empty cells on either end)
int[] inputArray = new int[cell.Length + 2];
//Copy the cell array into the new input array leaving the value of the first and last indexes as zero (empty cells)
Array.Copy(cell, 0, inputArray, 1, cell.Length);
//This is cool I stole this from the guy above! (cheers mate), this decrements the day count while checking that we are still above zero.
while (day-- > 0)
{
int oldCellValue = 0;
//In this section we loop through the array starting at the first real cell and going to the last real cell
//(we are not including the empty cells at the ends which are always inactive/0)
for (int i = 1; i < inputArray.Length - 1; i++)
{
//if the cells below and above our current index are the same == then the target cell will be inactive/0
//otherwise if they are different then the target cell will be set to active/1
//NOTE: before we change the index value to active/inactive state we are saving the cells oldvalue to a variable so that
//we can use that to do the next "cell competition" comparison (this fulfills the requirement to update the values at the same time)
if (oldCellValue == inputArray[i + 1])
{
oldCellValue = inputArray[i];
inputArray[i] = 0;
}
else
{
oldCellValue = inputArray[i];
inputArray[i] = 1;
}
}
}
//Finally we create a new output array that doesn't include the empty cells on each end
//copy the input array to the output array and Bob's yer uncle ;)...(comments are lies)
int[] outputArray = new int[cell.Length];
Array.Copy(inputArray, 1, outputArray, 0, outputArray.Length);
return outputArray;
}
With C#
public static int[] cellCompete(int[] states, int days)
{
if (days == 0) return states;
int leftValue = 0;
int rigthValue = 0;
for (int i = 0; i < states.Length; i++)
{
if (i == states.Length - 1)
rigthValue = 0;
else
rigthValue = states[i + 1];
if (leftValue == rigthValue){
leftValue = states[i];
states[i] = 0;
}
else{
leftValue = states[i];
states[i] = 1;
}
}
cellCompete(states, days - 1);
return states;
}
I think some of the answers above could be more readable (in addition to being more efficient). Use an additional array and alternate updates between them depending on the number of days. You can return the most recently updated array, which will always be the correct one. Like this:
function cellCompete(states, days) {
const newStates = [];
let originalStates = true;
while (days--) {
changeStates(
originalStates ? states : newStates,
originalStates ? newStates : states,
states.length
);
originalStates = !originalStates;
}
return originalStates ? states : newStates;
}
function changeStates(states, newStates, len) {
newStates[0] = !states[1] ? 0 : 1;
newStates[len-1] = !states[len-2] ? 0 : 1;
for (let i = 1; i < len - 1; i++) {
newStates[i] = states[i-1] === states[i+1] ? 0 : 1;
}
}
Here is my solution in c++ using bitwise operators :
#include <iostream>
using namespace std;
void cellCompete( int *arr, int days )
{
int num = 0;
for( int i = 0; i < 8; i++ )
{
num = ( num << 1 ) | arr[i];
}
for( int i = 0; i < days; i++ )
{
num = num << 1;
num = ( ( ( num << 1 ) ^ ( num >> 1 ) ) >> 1 ) & 0xFF;
}
for( int i = 0; i < 8; i++ )
{
arr[i] = ( num >> 7 - i ) & 0x01;
}
}
int main()
{
int arr[8] = { 1, 0, 0, 0, 0, 1, 0, 0};
cellCompete( arr, 1 );
for(int i = 0; i < 8; i++)
{
cout << arr[i] << " ";
}
}
#include <stdio.h>
int main() {
int days,ind,arr[8],outer;
for(ind=0;ind<8;scanf("%d ",&arr[ind]),ind++); //Reading the array
scanf("%d",&days);
int dupArr[8];
for(outer=0;outer<days;outer++){ //Number of days to simulate
for(ind=0;ind<8;ind++){ //Traverse the whole array
//cells on the ends have single adjacent cell, so the other adjacent cell can be assumsed to be always inactive
if(ind==0){
if(arr[ind+1]==0)
dupArr[ind]=0;
else
dupArr[ind]=1;
}
else if(ind==7){
if(arr[ind-1]==0)
dupArr[ind]=0;
else
dupArr[ind]=1;
}
else{
if((arr[ind-1]==0&&arr[ind+1]==0) || (arr[ind-1]==1&&arr[ind+1]==1)){// if its neighbours are both active or both inactive, the cell becomes inactive the next day
dupArr[ind]=0;
}
else //otherwise it becomes active the next day
dupArr[ind]=1;
}
}
for(ind=0;ind<8;ind++){
arr[ind]=dupArr[ind]; //Copying the altered array to original array, so that we can alter it n number of times.
}
}
for(ind=0;ind<8;ind++)
printf("%d ",arr[ind]);//Displaying output
return 0;
}
Here is my code which i had created some months ago,
You want to create two different arrays, because altering same array element will gives you different results.
func competeCell(cell []uint, days uint) []uint{
n := len(cell)
temp := make([]uint, n)
for i :=0; i < n; i ++ {
temp[i] = cell[i]
}
for days > 0 {
temp[0] = 0 ^ cell[1]
temp[n-1] = 0 ^ cell[n-2]
for i := 1; i < n-2 +1; i++ {
temp[i] = cell[i-1] ^ cell[i +1]
}
for i:=0; i < n; i++ {
cell[i] = temp[i]
}
days -= 1
}
return cell
}
Using c++
#include <list>
#include <iterator>
#include <vector>
using namespace std;
vector<int> cellCompete(int* states, int days)
{
vector<int> result1;
int size=8;
int list[size];
int counter=1;
int i=0;
int temp;
for(int i=0;i<days;i++)//computes upto days
{
vector<int> result;
if(states[counter]==0)
{
temp=0;
list[i]=temp;
//states[i]=0;
result.push_back(temp);
}
else
{
temp=1;
list[i]=temp;
result.push_back(temp);
}
for(int j=1;j<size;j++)
{
if(j==size)
{
if(states[j-1]==0)
{
temp=0;
list[j]=temp;
//states[i]=1;
result.push_back(temp);
}
else
{
temp=1;
list[i]=temp;
//states[i]=1;
result.push_back(temp);
}
}
else if(states[j-1]==states[j+1])
{
temp=0;
list[j]=temp;
//states[i]=1;
result.push_back(temp);
}
else
{
temp=1;
list[j]=temp;
//states[i]=1;
result.push_back(temp);
}
}
result1=result;
for(int i=0;i<size;i++)
{
states[i]=list[i];
}
}
return result1;
}
Java solution
This is solution is Java, which will work any number of Cells and any number of days .
public class Solution
{
public List<Integer> cellCompete(int[] states, int days)
{
List<Integer> inputList = new ArrayList<Integer>();
List<Integer> finalList = new ArrayList<Integer>();
// Covert integer array as list
for (int i :states)
{
inputList.add(i);
}
// for loop for finding status after number of days.
for(int i=1; i<= days; i++)
{
if(i==1)
{
finalList = nextDayStatus(inputList);
}
else
{
finalList = nextDayStatus(finalList);
}
}
return finalList;
}
// find out status of next day, get return as list
public List<Integer> nextDayStatus(List<Integer> input)
{
List<Integer> output = new ArrayList<Integer>();
input.add(0,0);
input.add(0);
for(int i=0; i < input.size()-2; i++)
{
if (input.get(i) == input.get(i+2))
{
output.add(0);
}
else
{
output.add(1);
}
}
return output;
}
}
I know this has been answered, but I gave it a go in Java and am pretty sure it will work for any size states array along with number of days:
public class CellCompete {
public static List<Integer> cellCompete(int[] states, int days) {
List<Integer> resultList = new ArrayList<>();
int active = 1, inactive = 0;
int dayCount = 1;
// Execute for the given number of days
while (days > 0) {
int[] temp = new int[states.length];
System.out.print("Day " + dayCount + ": ");
// Iterate through the states array
for (int i = 0; i < states.length; i++) {
// Logic for first end cell
if (i == 0) {
temp[i] = states[i + 1] == active ? active : inactive;
resultList.add(temp[i]);
System.out.print(temp[i] + ", ");
}
// Logic for last end cell
if (i == states.length - 1) {
temp[i] = states[i - 1] == active ? active : inactive;
resultList.add(temp[i]);
System.out.println(temp[i]);
}
// Logic for the in between cells
if (i > 0 && i < states.length - 1) {
if ((states[i - 1] == active && states[i + 1] == active) || (states[i - 1] == inactive && states[i + 1] == inactive)) {
temp[i] = inactive;
} else {
temp[i] = active;
}
resultList.add(temp[i]);
System.out.print(temp[i] + ", ");
}
}
dayCount++;
days--;
// Reset the states array with the temp array
states = temp;
}
return resultList;
}
public static void main(String[] args) {
int[] states = {1, 1, 0, 1, 0, 1, 0, 0};
int days = 5;
// Total of 40
System.out.println(cellCompete(states, days) );
}
}
Where did the people who wanted optimized solutions go?
def Solution(states, days):
for i in range(days):
for j in range(len(states)):
if (j == 0):
states[i] = states[1]
elif (j == len(states)-1):
states[i] = states[-2]
else:
states[i] = abs(states[i-1] - states[i+1])
return states
By definition, all the cells, including non-existent ones, are in fact booleans:
var cellUpdate = (cells, days) => {
let result = [];
// update states
for(let i = 0; i < cells.length; i++) result.push((!Boolean(cells[i-1]) === !Boolean(cells[i+1])) ? 0 : 1) ;
// repeat for each day
if (days > 1) result = cellUpdate(result, days - 1);
return result;
Here is the best python Solution
value=input()
n=int(input())
lst=[]
for i in value:
if "1"in i:
lst.append(1)
elif "0" in i:
lst.append(0)
for _ in range(n):
store = []
for i in range(8):
if i==0:
store.append(lst[i+1])
elif i==7:
store.append(lst[i-1])
elif lst[i-1]==lst[i+1]:
store.append(0)
else:
store.append(1)
lst=store
print(store)
Scala solution:
def cellDayCompete(cells: Seq[Int]): Seq[Int] = {
val addEdges = 0 +: cells :+ 0
(addEdges.dropRight(2) zip addEdges.drop(2)).map {
case (left, right) =>
(left - right).abs
}
}
def cellCompete(cells: Seq[Int], days: Int): Seq[Int] = {
if (days == 0) {
cells
} else {
cellCompete(cellDayCompete(cells), days - 1)
}
}
A code run with the example above can be found at Scastie
Just answered this question today and here was my solution in python3
def cellCompete(states, days):
for i in range(0, days):
#this is where we will hold all the flipped states
newStates = []
'''
Algo: if neigbors are the same, append 0 to newStates
if they are different append 1 to newStates
'''
for currState in range(len(states)):
#left and right ptr's
left = currState - 1
right = currState + 1
#if at beginning of states, left is automatically inactive
if left < 0:
if states[right] == 1:
newStates.append(1)
else:
newStates.append(0)
#if at end of states, right is automatically inactive
elif right > 7: #we know there is always only 8 elems in the states list
if states[left] == 1:
newStates.append(1)
else
newStates.append(0)
#check to see if neighbors are same or different
elif states[left] != states[right]:
newStates.append(1)
else:
newStates.append(0)
#Set the states equal to the new flipped states and have it loop N times to get final output.
states = newStates
return states
def cellCompete(states, days):
d = 0
l = len(states)
while d < days:
new_states = [0] * l
for i in range(l):
if i == 0 and states[i+1] == 0 or i == l - 1 and states[i-1] == 0:
new_states[i] = 0
elif i == 0 and states[i+1] == 1 or i == l - 1 and states[i-1] == 1:
new_states[i] = 1
elif states[i+1] == states[i-1]:
new_states[i] = 0
else:
new_states[i] = 1
states = new_states
d = d + 1
return states
static int[] CellCompete(int[] states, int days)
{
int e = states.Length;
int[] newStates = new int[(e+2)];
newStates[0] = 0;
newStates[e+1] = 0;
Array.Copy(states, 0, newStates, 1, e);
for (int d = 0; d < days; d++)
{
states = Enumerable.Range(1, e).Select(x => newStates[x - 1] ^ newStates[x + 1]).ToArray();
newStates[0] = 0;
newStates[e + 1] = 0;
Array.Copy(states, 0, newStates, 1, e);
}
return states;
}
//Here is a working solution for this problem in C#
public class HousesinSeq
{
private string _result;
public string Result
{
get { return _result; }
}
public void HousesActivation(string houses, int noOfDays)
{
string[] housesArr = houses.Split(' ');
string[] resultArr = new string[housesArr.Length];
for (int i = 0; i < noOfDays; i++)
{
for (int j = 0; j < housesArr.Length; j++)
{
if (j == 0)
{
if (housesArr[j + 1] == "0")
{
resultArr[j] = "0";
}
else
{
resultArr[j] = "1";
}
}
else if (j == housesArr.Length - 1)
{
if (housesArr[j - 1] == "0")
{
resultArr[j] = "0";
}
else
{
resultArr[j] = "1";
}
}
else
{
if (housesArr[j + 1] == housesArr[j - 1])
{
resultArr[j] = "0";
}
else
{
resultArr[j] = "1";
}
}
}
resultArr.CopyTo(housesArr, 0);
}
foreach (var item in resultArr)
{
//Console.Write($"{item} ");
_result += item + " ";
}
_result = _result.Trim();
}
}
public class Colony {
public static int[] cellCompete(int[] cell, int day) {
int[] ar = new int[10];
for(int i=1; i<9; i++) {
ar[i] = cell[i-1];
}
while(day-- >0) {
int temp = 0;
for(int i=1; i<9; i++) {
if(Math.abs(temp-ar[i+1])==1) {
temp = ar[i];
ar[i] = 1;
}
else {
temp = ar[i];
ar[i] = 0;
}
}
}
return ar;
}
public static void main(String[] args) {
int[] cell = {1,0,1,1,0,1,0,1};
int day = 1;
cell = cellCompete(cell, day);
for(int i=1; i<9; i++) {
System.out.print(cell[i]+" ");
}
}
}

Boolean fuction to all the elements in an array processing 3.0

I'm trying to make a program which shows some circles, and when the user puts all the circles in one place, the background changes. The problem I have is that when one circle is moved to that place the background changes, but I need that to happened once all the elements of the array had changed position..
DragMe[] drags = new DragMe[15];
PGraphics topLayer;
PGraphics toperLayer;
color backgr;
void setup() {
size(500, 500);
for (int i = 0; i < drags.length; i++) {
drags[i] = new DragMe();
}
topLayer = createGraphics(width, height, g.getClass().getName());
}
void draw() {
background(backgr);
{
topLayer.beginDraw();
topLayer.noFill();
topLayer.stroke(0 );
if (mousePressed ==true) {
topLayer.line( pmouseX, pmouseY, mouseX, mouseY );
topLayer.endDraw();
}
image( topLayer, 0, 0 );
}
for (int i = 0; i < drags.length; i++) {
drags[i].display();
drags[i].update();
}
for (int i = 0; i < drags.length; i++) {
drags[i].fondo();
}
{
ellipse(width/2.5, height/2.5, 110, 110);
fill(255);
}
}
void mousePressed() {
for (int i = 0; i < drags.length; i++) {
if (!drags[i].isOver())
drags[i].dontMove = true;
drags[i].offset_x = mouseX - drags[i].pos_x;
drags[i].offset_y = mouseY - drags[i].pos_y;
}
}
void mouseReleased() {
for (int i = 0; i < drags.length; i++) {
drags[i].locked = false;
drags[i].dontMove = false;
}
}
class DragMe {
float pos_x, pos_y, SIZE = 25;
float prev_x, prev_y;
boolean locked;
boolean dontMove;
boolean all;
color c = color (255);
float offset_x, offset_y;
DragMe() {
pos_x = random(width-SIZE);
pos_y = random(height-SIZE);
}
void update() {
if (isOver() && !locked && !dontMove || locked && !dontMove )
c = color (255);
else
c = color (255);
if (isClicked()) {
locked = true;
}
if (isIn()) {
locked = false;
all = true;
}
if (locked && !dontMove) {
pos_x = mouseX - offset_x;
pos_y = mouseY - offset_y;
}
}
void display() {
fill(c);
ellipse(pos_x, pos_y, SIZE, SIZE);
ellipseMode(CORNER);
noStroke();
}
boolean isOver() {
float right_x = pos_x + SIZE;
float bottom_y = pos_y + SIZE;
return mouseX >= pos_x && mouseX <= right_x &&
mouseY >= pos_y && mouseY <= bottom_y;
}
boolean isClicked() {
return isOver() && mousePressed && !dontMove;
}
boolean isIn() {
float right_x = pos_x + SIZE;
float bottom_y = pos_y + SIZE;
return right_x >= width/2.5 + SIZE && right_x <= width/2.5 + 100 &&
bottom_y >= height/2.5 + SIZE && bottom_y <= height/2.5 + 100;
}
void fondo() {
if (all == true)
backgr= 255;
}
}
You have 15 instances of DragMe.
Each of those instances contains a variable named all.
When one instance's all is true, you set the background to white.
Specifically, this function:
void fondo() {
if (all == true)
backgr= 255;
}
Which you call from draw():
for (int i = 0; i < drags.length; i++) {
drags[i].fondo();
}
Instead, you need to check every instance's all variable, and only change the background if they are all true (in other words, if none of them are false):
boolean allIn = true;
for (int i = 0; i < drags.length; i++) {
if (!drags[i].all) {
allIn = false;
}
}
if (allIn) {
backgr= 255;
}
For future questions, please try to make sure your code is formatted. It might also be a good idea to use better variable names- naming a variable all is a bit hard to talk about. Maybe something like isInsideWhiteCircle would be better.

simple word search java 2d arrays

Im a begginner and i was wondering if anyone could tell me what im doing wrong here with this word search ?
im stuck on checking each row for a word specified in the formal argument, currently it doesnt do any checks of any sort its jst a basic boolean method which returns true if a word is found within a row of the array.assuming the word search array is rectangular
public boolean checkRow( char[][] puzzle, String w)
{
int counter = 0;
boolean match = true;
for ( int row = 0; row < puzzle.length; row++)
{
counter = 0;
for ( int col = 0; col < puzzle[row].length; col++)
{
if ( counter <= w.length() )
{
char word = puzzle[row][col];
if( w.charAt(counter) == word)
{
match = true;
counter++;
}
}
else if ((counter == w.length()) && (match == true))
{
return true;
}
else
{
match = false;
counter = 0;
}
}
}
return match;
}
Here is your code corrected
public boolean checkRow(char[][] puzzle, String w) {
int counter = 0;
boolean match = true;
for (int row = 0; row < puzzle.length; row++) {
counter = 0;
match = false;
for (int col = 0; col < puzzle[row].length; col++) {
if (counter < w.length()) {
char word = puzzle[row][col];
if (w.charAt(counter) == word) {
match = true;
counter++;
} else {
match = false;
counter = 0;
}
if ((counter == w.length()) && (match == true)) {
return true;
}
}
}
}
return false;
}
but this is not the best way how to do your check, here is much smoother and even faster (about 5 times, i'd test it) code
public boolean checkRow2(char[][] puzzle, String w) {
String rowStr = null;
for(int row = 0; row < puzzle.length; row++) {
rowStr = new String(puzzle[row]);
if(rowStr.contains(w)) return true;
}
return false;
}

Resources