Converting function to use iteration - c
I have written a recursive function to access array elements. Every 2nd, 3rd, 4th, and so on to 150. I want to do the same thing but with iteration. I have coded something below, the first example it runs but i'm not sure its correct and works the same as the first function. I know i'm using two for loops to do this i may have placed the index var in wrong spot.
void openarray(skip)
{
int i;
for(i = skip; i < 150; i+=skip + 1)
{
if(arrayB[i] == open)
{
arrayB[i] = close;
}
else
{
arrayB[i] = open;
}
}
if(skip < 150)
{
openarray(skip + 1);
}
}
my code to turn into iteration i think i may have confused the index for step or vice versa.
int i, j;
for(i = 0; i < 150; i++)
{
for (j = 0; j < 150; j+=i + 1)
if(arrayB[i] == open)
{
arrayB[i] = close;
}
else
{
arrayB[i] = open;
}
}
Step 1: Let's put the recursive call at the very end.
void openarray(skip)
{
int i;
for(i = skip; i < 150; i+=skip + 1)
{
if(arrayB[i] == open)
{
arrayB[i] = close;
}
else
{
arrayB[i] = open;
}
}
if(skip >= 150)
return;
openarray(skip + 1);
}
Step 2: Add the loop.
void openarray(skip)
{
while (1) {
int i;
for(i = skip; i < 150; i+=skip + 1)
{
if(arrayB[i] == open)
{
arrayB[i] = close;
}
else
{
arrayB[i] = open;
}
}
if(skip >= 150)
return;
skip = skip + 1;
}
}
Step 3: Clean up
void openarray(skip)
{
for (; skip < 150; ++skip)
{
int i;
for(i = skip; i < 150; i+=skip + 1)
{
if(arrayB[i] == open)
{
arrayB[i] = close;
}
else
{
arrayB[i] = open;
}
}
}
}
We can compare this against your code to see what errors you made:
You initialized the outer loop counter to zero.
You used the outer loop counter as the array index instead of the inner loop counter.
Related
School program tests not covering my code correctly and I'm not sure why
This might be inappropriate but I'm working on a school project in university and we use an automated test service called Web-Cat. When I upload my file (everything is correct as for the filename and method names etc.) the tests throw this at me: hint: your code/tests do not correctly cover error: Cannot locate behavioral analysis output. My code looks like this, I can't find any compile errors or anything that would cause such a problem. #include <stdio.h> double getPositiveAverage(double array[], int numItems) { double average = 0; int numOfItems = 0; for (int i = numItems-1; i >= 0; i--) { if (array[i] > 0) { average = average + array[i]; numOfItems++; } } if (numOfItems == 0) { return 0; } else { return average / numOfItems; } } int countRangeValues(double array[], int numItems, double count) { double countPlus = count + .5; double countMinus = count - .5; int counter = 0; for (int i = numItems-1; i >= 0; i--) { if ((array[i] >= countMinus) && (array[i] < countPlus)) { counter++; } } return counter; } double getMaxAbsolute(double array[], int numItems) { double max = 0; for (int i = numItems-1; i >= 0; i--) { if (array[i] == max * -1 && array[i] > 0) { max = array[i]; } else if (array[i] < 0) { if (max < 0) { if ((array[i] * -1) > (max * -1)) { max = array[i]; } } else { if ((array[i] * -1) > max) { max = array[i]; } } } else { if (max < 0) { if ((array[i]) > (max * -1)) { max = array[i]; } } else { if ((array[i]) > max) { max = array[i]; } } } } return max; } int countInverses(int array[], int numItems) { int negarray[numItems]; int negItems = 0; int posarray[numItems]; int posItems = 0; int counter = 0; for (int i = numItems-1; i >= 0; i--) { if (array[i] < 0) { negarray[negItems] = array[i]; negItems++; } else if(array[i] > 0) { posarray[posItems] = array[i]; posItems++; } } if (posItems == 0 || negItems == 0) { return 0; } else { if (posItems > negItems) { for (int i = posItems-1; i >= 0; i--) { for (int j = negItems-1; j >= 0; j--) { if ((negarray[j]*-1) == posarray[i] && negarray[j] != 0) { counter++; negarray[j] = 0; posarray[i] = 0; } } } } } return counter; } int getMaxCount(double array[], int numItems) { return countRangeValue(array, numItems, getMaxAbsolute(array, numItems)); } If necessary, I can explain the purpose of all of these methods but the test also says "Your program failed before running any tests. Usually this is a compile problem or premature exit problem. Make sure your program compiles and runs before uploading." So I assume its syntax a compiling problem, I just don't know if anything I did would cause something like that.
Candidate problems: Compilation error #fussel // return countRangeValue(array, numItems, getMaxAbsolute(array, numItems)); return countRangeValues(array, numItems, getMaxAbsolute(array, numItems)); Missing main() #Bob__. Variable length arrays are OK #Eric Postpischil in C99 and optionally in C11 yet do not attempt without insuring a positive array size. int countInverses(int array[], int numItems) { if (numItems <= 0) { return 0; } int negarray[numItems]; .... Instead of if (posItems > negItems) { I'd expect if (posItems >= negItems) { or maybe even if (1), yet the goal of countInverses() lacks details for deep analysis. countRangeValues(..., double count) is suspicious with double count. When count is a large value, countPlus == count and countMinus == count. The function always returns 0 as array[i] >= countMinus) && (array[i] < countPlus) is always false. OP's getMaxAbsolute() looks too convoluted. Suggested alternative: double getMaxAbsolute(const double array[], int numItems) { double max = 0.0; double amax = 0.0; for (int i = numItems - 1; i >= 0; i--) { double aelement = fabs(array[i]); // If greater or the same, favor + over - if (aelement > amax || (aelement == amax && array[i] > max)) { max = array[i]; amax = aelement; } } return max; }
Function to swap two adjacent elements isn't working
When I try to move a legal tile (i.e one adjacent to the 'blank' tile 0), nothing happens. If the tile is illegal the program functions as it should. Here is the move function: bool move(int tile) { for (int i = 0; i < d; i++) { for (int j = 0; j < d; j++) { if (board[i][j] == tile) { // stops program from going out of bounds if (j < d) { if (board[i][j + 1] == 0) { swap(board[i][j], board[i][j + 1]); return true; } } if (j > 0) { if (board[i][j - 1] == 0) { swap(board[i][j], board[i][j - 1]); return true; } } if (i > 0) { if (board[i - 1][j] == 0) { swap(board[i][j], board[i - 1][j]); return true; } } if (i < d) { if (board[i + 1][j] == 0) { swap(board[i][j], board[i + 1][j]); return true; } } } } } return false; } and the swap function: void swap(int i, int j) { int temp = i; i = j; j = temp; } What happens is the board remains looking the same with no changes made.
You need to use pointers to change the memory at board[i][j]. Try something like this void swap(int *i, int *j) { int temp = *i; *i = *j; *j = temp; } and then in your calling code swap(&board[i][j], &board[i][j - 1]);
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]+" "); } } }
C algorithm to try out all the possible combinations of 12 knights in a chess board
I have been writing this program that tries to find how to put 12 knights on a chess board so all squares are either taken up by a knight or one of 12 knights can reach them in one move. So far I have created 2 functions: one takes a board with 12 knights and fills all the squares they can reach with 'T' and another that takes a filled chess board and checks if there are left any squares not taken up by a knight nor dominated by it (meaning no knight can reach it in one move). Now I am dealing with the problem of how can I try out all the possible combinations of knights. My idea is that after every single combination of 12 knights on a board, I will send the board with 12 knights to be filled with 'T's for all the squares they can reach, and then send it to another function to check if all squares are dominated. Here is my code: #include <stdio.h> #include <stdlib.h> int filling(char array[8][8]) { int i, j; for (i = 0;i < 8;i++) { for (j = 0; j < 8;j++) { if(array[i][j] == 'H') { if(i-1>-1 && j+2<8 && array[i-1][j+2]!='H') array[i-1][j+2]='T'; if(i+1<8 && j+2<8 && array[i+1][j+2]!='H') array[i+1][j+2]='T'; if(i-2>-1 && j+1<8 && array[i-2][j+1]!='H') array[i-2][j+1]='T'; if(i+2<8 && j+1<8 && array[i+2][j+1]!='H') array[i+2][j+1]='T'; if(i-2>-1 && j-1>-1 && array[i-2][j-1]!='H') array[i-2][j-1]='T'; if(i+2<8 && j-1>-1 && array[i+2][j-1]!='H') array[i+2][j-1]='T'; if(i-1>-1 && j-2>-1 && array[i-1][j-2]!='H') array[i-1][j-2]='T'; if(i+1<8 && j-2>-1 && array[i+1][j-2]!='H') array[i+1][j-2]='T'; } } } } int checking(char array[8][8]) { int i, j; for(i = 0;i < 8;i++) { for(j = 0;j < 8;j++) { if(array[i][j] != 'H' && array[i][j] != 'T') return 0; } } return 1; } int main() { int i, j; char board[8][8]; for(i = 0; i < 8; i++) { for(j = 0; j < 8; j++) board[i][j] = '0'; } // The following lines are here to test if the checking and filling work /*board[2][1] = 'H'; board[2][2] = 'H'; board[3][2] = 'H'; board[5][2] = 'H'; board[6][2] = 'H'; board[5][3] = 'H'; board[2][4] = 'H'; board[1][5] = 'H'; board[2][5] = 'H'; board[4][5] = 'H'; board[5][5] = 'H'; board[5][6] = 'H'; */ filling(board); if(checking(board) == 1) printf (" \n Works"); else printf ("\n Doesnt work"); for(i = 0; i < 8; i++) { printf("\n"); for(j = 0; j < 8; j++) printf("%c ", board[i][j]); } return 0; } What kind of algorithm I could use to try out every combo? Thank you for your answers.
You need these things: A sorting rule that puts all possible combinations in a well-defined order. An initialization rule that defines the board's first such combination. An increment rule that transitions a board from its current combination to the next combination in the well-defined order. A rule that detects when the board is in the last combination. Then you just use algorithm 2 to put the board in the first state. Then check with algorithm 4 to see if you're in the last state. If not, use algorithm 3 to go to the next state. Algorithm 1 is probably the hard one. One simple rule is just to convert the board's position to a binary number with a zero for an empty square and a one for a full square in a well-defined order, say starting from the top left and going across, then moving to the next row.
If you're on decent, or even semi-decent hardware, you've got a 64-bit unsigned integral type available to you. Let's call that uint64_t. You can store a chessboard with knight positions as a single uint64_t. You can also store a "dominated" mask in the same type. You simply establish a correlation between the 64 bits in the type and the 64 spaces on the chessboard. Since there are 64 possible locations, you can pre-compute the possible threat masks for each position, storing that as an array of 64 uint64_t values. You need to set the position of each knight. But you can safely do them in a certain order, so that knight #1 is always the "highest" knight - his bit position is always highest, or lowest, or whatever. So you could write code like this: for (k0 = 64; k0 > 11; --k0) for (k1 = k0 - 1; k1 > 10; --k1) for (k2 = k1 - 1; k2 > 9; --k2) ... for (k11 = k10 - 1; k11 >= 0; --k11) /* do stuff */ But that's horrible, because there are a squillion possibilities (squillion = 1573144097507348889600, thanks #jwd!). That said, the threat mask for each knight can be computed "incrementally" from the masks of the outer knights, so it might be faster to perform all the computations than to try to store/mark/compute the rotations and flips of the board. Something like this: for (kXX = kYY - 1; kXX > (11-XX); --kXX) { threat_XX = threat_YY | pre_computed_threat[kXX]; for (kZZ = KXX - 1; kZZ > (11-ZZ); --kZZ) { threat_ZZ = threat_XX | pre_computed_threat[kZZ]; The nice thing about this approach is that your objective is total coverage by threats - all 1 bits in the threat_11 map, in other words. You can test just by inverting the bits and comparing with zero.
Well thanks to my questions of today I got myself blocked from asking more until my rep gets better, but for what its worth I managed to solve the problem myself. I had to take 3 positions in each quarter of the board that can only be reached by seperate horses, that way making my 12 for cycles shorter, as they only had to go through specific locations, instead of trying every single of of them. The execution times is just above one second and it finds two different layouts for 12 knights, marking them 'H' and the positions they can reach in one turn 'T'. Here is the code if anyone ever comes to a problem like this: #include <stdio.h> #include <stdlib.h> struct horses { int x; int y; }; void fill(struct horses arkliai[12], char array[8][8]) { int i,j; for(i = 0; i < 8; i++) { for(j = 0; j < 8; j++) array[i][j] = '0'; } for(i = 0; i < 12; i++) { array[arkliai[i].x][arkliai[i].y] = 'H'; } pildymas(array); } void startingpositions(struct horses arkliai[12]) { int i = 0; int j = 0; int a = 0; for(a = 0; a < 12; a++) { if(i > 7) { i = 0; j++; } arkliai[a].x = i; arkliai[a].y = j; i++; } } void combinacijos(struct horses h[12], char array[8][8]) { int a,b,c,d,e,f,g,hi,ii,ji,k,l; for(a = 0; a < 2; a++) { if(a == 0) { h[0].x = 1; h[0].y = 2; } if(a == 1) { h[0].x = 2; h[0].y = 1; } for(b = 0; b < 2; b++) { if(b == 0) { h[1].x = 5; h[1].y = 1; } if(b == 1) { h[1].x = 6; h[1].y = 2; } for(c = 0; c < 2; c++) { if(c == 0) { h[2].x = 1; h[2].y = 5; } if(c == 1) { h[2].x = 2; h[2].y = 6; } for(d = 0; d <2;d++) { if(d == 0) { h[3].x = 5; h[3].y = 6; } if(d == 1) { h[3].x = 6; h[3].y = 5; } for(e = 0; e < 3; e++) { if(e == 0) { h[4].x = 2; h[4].y = 0; } if(e == 1) { h[4].x = 2; h[4].y = 2; } if(e == 2) { h[4].x = 1; h[4].y = 3; } for (f = 0; f < 3; f++) { if(f == 0) { h[5].x = 1; h[5].y = 4; } if(f == 1) { h[5].x = 2; h[5].y = 5; } if(f == 2) { h[5].x = 2; h[5].y = 7; } for (g = 0; g < 3; g++) { if(g == 0) { h[6].x = 5; h[6].y = 7; } if(g == 1) { h[6].x = 5; h[6].y = 5; } if(g == 2) { h[6].x = 6; h[6].y = 4; } for(hi = 0; hi < 3; hi++) { if(hi == 0) { h[7].x = 5; h[7].y = 0; } if(hi == 1) { h[7].x = 5; h[7].y = 2; } if(hi == 2) { h[7].x = 6; h[7].y = 3; } for(ii = 0; ii < 4; ii++) { if (ii == 0) { h[8].x = 3; h[8].y = 0; } if (ii == 1) { h[8].x = 3; h[8].y = 2; } if (ii == 2) { h[8].x = 0; h[8].y = 3; } if (ii == 3) { h[8].x = 2; h[8].y = 3; } for(ji = 0; ji < 4; ji++) { if (ji == 0) { h[9].x = 3; h[9].y = 7; } if (ji == 1) { h[9].x = 3; h[9].y = 5; } if (ji == 2) { h[9].x = 2; h[9].y = 4; } if (ji == 3) { h[9].x = 0; h[9].y = 4; } for(k = 0; k < 4; k++) { if (k == 0) { h[10].x = 4; h[10].y = 7; } if (k == 1) { h[10].x = 4; h[10].y = 5; } if (k == 2) { h[10].x = 5; h[10].y = 4; } if (k == 3) { h[10].x = 7; h[10].y = 4; } for(l = 0;l < 64;l++) { if(h[11].x == 7) { if(h[11].y == 7) { h[11].x = 0; h[11].y = 0; break; } h[11].x = 0; h[11].y = h[11].y +1; } else { h[11].x= h[11].x+1; } fill(h, array); } } } } } } } } } } } } } int pildymas(char array[8][8]) { int i, j; for (i = 0;i < 8;i++) { for (j = 0; j < 8;j++) { if(array[i][j] == 'H') { if(i-1>-1 && j+2<8 && array[i-1][j+2]!='H') array[i-1][j+2]='T'; if(i+1<8 && j+2<8 && array[i+1][j+2]!='H') array[i+1][j+2]='T'; if(i-2>-1 && j+1<8 && array[i-2][j+1]!='H') array[i-2][j+1]='T'; if(i+2<8 && j+1<8 && array[i+2][j+1]!='H') array[i+2][j+1]='T'; if(i-2>-1 && j-1>-1 && array[i-2][j-1]!='H') array[i-2][j-1]='T'; if(i+2<8 && j-1>-1 && array[i+2][j-1]!='H') array[i+2][j-1]='T'; if(i-1>-1 && j-2>-1 && array[i-1][j-2]!='H') array[i-1][j-2]='T'; if(i+1<8 && j-2>-1 && array[i+1][j-2]!='H') array[i+1][j-2]='T'; } } } tikrinimas(array); } int tikrinimas(char array[8][8]) { int i, j; for(i = 0;i < 8;i++) { for(j = 0;j < 8;j++) { if(array[i][j] != 'H' && array[i][j] != 'T') return 0; } } printas(array); } int printas(char array[8][8]) { int i,j; for(j = 0; j <8; j++) { printf("\n"); for(i = 0; i <8 ; i++) printf("%c ", array[i][7-j]); } printf("\n"); } int main() { struct horses hr[12]; char board[8][8]; startingpositions(hr); combinacijos(hr, board); return 0; }
Error in a "for" loop, I think memory problems
I'm trying to create an algorithm that loops through the loop 'for' ten times, the ultimate goal is to print out a 50x50 matrix with the sum of the values greater than or equal to 49, 0, and 1 represented as '*', but for some strange reason the loop only does 3 iterations instead of 10. .. #include <stdio.h> void printsimulaciodeu(int matlefa[50][50]) { int ii, jj; for (ii = 0; ii < 50; ii++) { for (jj = 0;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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, }; int its; int i, j; int disparos_pos[10] = {1, 5, 14, 22, 37, 48, 43, 40, 28, 19}; char disparos_dir[10]= {'i','i','d','i','d','d','i','d','d','i'}; int mataux[50][50]; for (i = 0; i < 50; i++) { for (j = 0; j < 50; j++) { mataux[i][j] = tabla[i][j]; } } int matsuma[50][50]; for (its = 0; its < 10; its++) { int pos = disparos_pos[its]; int dir = disparos_dir[its]; i = 0; j = pos; int cont = 49; while (i < 49) { if (mataux[i+1][j] == 0) { mataux[i+1][j] = cont; ++i; } else { if (dir == 'i') { if (mataux[i+1][j] != 0) { if (mataux[i][j-1] == 0) { mataux[i][j-1] = cont; --j; } else { dir = 'd'; } } } if (dir == 'd') { if (mataux[i+1][j] != 0) { if (mataux[i][j+1] == 0) { mataux[i][j+1] = cont; ++j; } else { dir = 'i'; } } } } } if (its == 0) { int m, n; for (m = 0; m < 50; m++) { for (n = 0; n < 50; n++) { matsuma[m][n] = mataux[m][n]; } } } if (its > 0) { int p, q; for (p = 0; p < 50; p++) { for (q = 0; q < 50; q++) { if (mataux[p][q] == 49) { if (matsuma[p][q] >= 49) { matsuma[p][q] = matsuma[p][q]+1; } } } } } } printsimulaciodeu(matsuma); } I thought that one possibility is that the memory for the process is complete and therefore not iterate correctly, is that possible? please help, I need it to work well for college work.
After a bit of debugging, I figured out the actual problem: Your while loop will run for INFINITE time in 3rd iteration of for loop. Explaination The while loop runs OK until i=33 at i=33 (j = 21, dir = 'i'), the none of the assignment statements (mataux[blah][blah] = blah balh) are executed, as conditons turn out to be false. Ultimate result is that value of 'dir' is toggled between 'i' and 'd', and the loop will run for forever!! Details mataux[i+1][j] = mataux[34][21] = 1 != 0 ---> first IF skipped mataux[i][j-1] = mataux[33][20] = 49 != 0 ---> third IF in first ELSE of WHILE skipped ELSE --> dir = 'd' (100) mataux[i][j+1] = mataux[33][22] = 1 != 0 ---> third IF in last IF block skipped ELSE --> dir = "i" (105) Hope this helps!