I'm working on a class project and here is what I have so far. I know the code returns true when it finds a match but I want it to keep looping until no more instances are found.
I've looked at numerous sites on for/while loops but I can't seem to get the syntax correct and/or it doesn't work when applying the logic.
public bool Remove(T toRemove)
{
for (int i = 0; i < count; i++)
{
if (items[i].Equals(toRemove))
{
int removeIndex = i;
for (int j = removeIndex; j < count - 1; j++)
{
items[j] = items[j + 1];
}
return true;
}
}
return false;
}
If you want to complete the loop, do not return. Instead hold the result on a var you should return at the end:
public bool Remove(T toRemove)
{
bool result = false;
for (int i = 0; i < count; i++)
{
if (items[i].Equals(toRemove))
{
int removeIndex = i;
for (int j = removeIndex; j < count - 1; j++)
{
items[j] = items[j + 1];
}
result = true;
}
}
return result;
}
Just save the result in a variable and return it after the loop is complete:
public bool Remove(T toRemove)
{
bool result = false;
for (int i = 0; i < count; i++)
{
if (items[i].Equals(toRemove))
{
int removeIndex = i;
for (int j = removeIndex; j < count - 1; j++)
{
items[j] = items[j + 1];
}
result = true;
}
}
return result;
}
//Use a boolean variable and set it to true if an item is found,
//and continue your loop until you go through all elements, then return the boolean value.
public bool Remove(T toRemove)
{
bool match= false; //boolean to track if any match is found
for (int i = 0; i < count; i++)
{
if (items[i].Equals(toRemove))
{
int removeIndex = i;
for (int j = removeIndex; j < count - 1; j++)
{
items[j] = items[j + 1];
}
match= true;
}
}
return match;
}
I think what you want to do is declare a bool called "result" and instantiate it to false. In the loop where you are returning true, set "result" to true. At the end, where you are returning false, return "result"
Related
I am working on an A* Pathfinding method that uses a custom class instead of nodes, but am having issues with my loops. The first for loop using int i is able to go up to 3 (Player1.instance.movement = 3), but I need to use an if statement inside of that loop to check if the target position has already been found. I am wondering if it is possible to break my for loop when my If statement is false.
public void GetNeighbors(Tile originTile)
{
Tile originalTile = originTile;
nextTile.Clear();
int minX = 0;
int minY = 0;
var originCostFunc = Mathf.Infinity;
for (int i = 0; i < Player1.instance.movement; i++)
{
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
if (x != y && y != x)
{
var costX = Mathf.Abs((originTile.transform.position.x + x) - originalTile.transform.position.x);
var costY = Mathf.Abs((originTile.transform.position.y + y) - originalTile.transform.position.y);
var distanceX = Mathf.Abs(targetPos.transform.position.x - (originTile.transform.position.x + x));
var distanceY = Mathf.Abs(targetPos.transform.position.y - (originTile.transform.position.y + y));
var costFunc = costX + costY + distanceX + distanceY;
if (costFunc <= originCostFunc)
{
originCostFunc = costFunc;
minX = x;
minY = y;
Debug.Log($"x: {x}, y: {y}");
}
}
}
}
nextTile.Add(GridManagerHandPlaced.instance.GetTileAtPosition(new Vector2(originTile.transform.position.x + minX, originTile.transform.position.y + minY)));
if (nextTile[i] != targetPos)
{
originTile = nextTile[i];
}
else
{
break;
}
}
DisplayPath();
}
You can break loop several times by condition.
bool breakLoop = false;
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
for (int k = 0; k < length; k++)
{
breakLoop = nextTile == target;
if (breakLoop)
break;
}
if (breakLoop)
break;
}
if (breakLoop)
break;
}
Or move search logic to separated method and return a value from any number of nested loops
string path = FindPath();
Display(path);
string FindPath()
{
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
for (int k = 0; k < length; k++)
{
if (nextTile == target)
return nextTile;
}
}
}
return null;
}
Never use goto operator.
This is one of the few valid cases where I'd use goto. In-fact, this is the example given in the docs for when it should be used.
void CheckMatrices(Dictionary<string, int[][]> matrixLookup, int target)
{
foreach (var (key, matrix) in matrixLookup)
{
for (int row = 0; row < matrix.Length; row++)
{
for (int col = 0; col < matrix[row].Length; col++)
{
if (matrix[row][col] == target)
{
goto Found;
}
}
}
Console.WriteLine($"Not found {target} in matrix {key}.");
continue;
Found:
Console.WriteLine($"Found {target} in matrix {key}.");
}
}
Note the syntax for the label is simply myLabel: and you can place it anywhere in procedurally executable code.
For sake of covering other ways of handling this situation, here is the boolean solution.
bool breakLoops = false;
for (int i = 0; i < length1; i++)
{
for (int ii = 0; ii < length2; ii++)
{
for (int iii = 0; iii < length3; iii++)
{
if (breakingCondition)
{
breakLoops = true;
break;
}
}
if (breakLoops) break;
}
if (breakLoops) break;
}
Simple and straightforward, but requires a break condition check at the end of each loop that you want to break out of.
I have to find subtext in text without using builtin function of string.
public static void Main(string[] args)
{
string subtext = "polly";
string text = "polly put the katle on,polly put the katle on,polly put the katle on,we all have tea";
int i, j, found;
int strLen, wordLen;
strLen = text.Length;
wordLen = subtext.Length;
for (i = 0; i < strLen - wordLen; i++)
{
found = 1;
for (j = 0; j < wordLen; j++)
{
if (text[i + j] != subtext[j])
{
found = 0;
break;
}
}
if (found == 1)
{
Console.WriteLine(" found at index:", subtext, i);
Console.ReadLine();
}
}
}
I am not sure how long you would like to search, your current code seems to find all indexes (or at least that seems to be the intent)
Some things you could change however is instead of always starting the loop, you could validate the if the char at position i matches the first char of the subtext, and if not continue.
When you want to write the data to the console, don't forget to add the spaceholders for your arguments, like:
Console.WriteLine("found {0} at index: {1}", subtext, i);
For the rest, I guess your current implementation is okay, but you could add some validations, like ensuring that both texts are available, and if subtext is longer than the text, simply return -1 directly.
For a simple find of first index, I wrote this one up, it still looks pretty similar to yours
private static int FindIn( string text, string sub ) {
if (string.IsNullOrWhiteSpace( text ) || string.IsNullOrWhiteSpace( sub ) ) {
return string.IsNullOrWhiteSpace( sub ) ? 0 : -1;
}
if (text.Length < sub.Length) {
return -1;
}
for (int i = 0; i < text.Length - sub.Length; i++) {
if (text[i] != sub[0]) {
continue;
}
var matched = true;
for (int j = 1; j < sub.Length && i + j < text.Length; j++) {
if (text[i+j] != sub[j]) {
matched = false;
break;
}
}
if (matched) {
return i;
}
}
return -1;
}
Which you can play around with here
There are a lot of pattern-matching algorithms in this book, i will leave here c# implementation of Knuth-Morris-Pratt algorithm.
static int[] GetPrefix(string s)
{
int[] result = new int[s.Length];
result[0] = 0;
int index = 0;
for (int i = 1; i < s.Length; i++)
{
while (index >= 0 && s[index] != s[i]) { index--; }
index++;
result[i] = index;
}
return result;
}
static int FindSubstring(string pattern, string text)
{
int res = -1;
int[] pf = GetPrefix(pattern);
int index = 0;
for (int i = 0; i < text.Length; i++)
{
while (index > 0 && pattern[index] != text[i]) { index = pf[index - 1]; }
if (pattern[index] == text[i]) index++;
if (index == pattern.Length)
{
return res = i - index + 1;
}
}
return res;
}
If you are looking for all occurance of the subtect in the text you can use the following code:
public static void Main(string[] args)
{
string subtext = "polly";
string text = "polly put the katle on,polly put the katle on,polly put the katle on,we all have tea";
int index = 0;
int startPosition = 0;
bool found = false;
while (index < text.Length - 1)
{
if (subtext[0] == text[index])
{
startPosition = index;
index++;
for (int j = 1; j <= subtext.Length - 1; j++)
{
if (subtext[j] != text[index])
{
found = false;
break;
}
else
{
found = true;
}
index++;
}
}
if (found)
{
Console.WriteLine("{0} found at index: {1}", subtext, startPosition);
found = false;
}
index++;
}
Console.ReadLine();
}
If you are looking only for the first occurance add break in the "if (found)" condition
Ok so I finished my code n queens genetics in c# but I keep getting these compiler errors even though I changed the code several times
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NQueen1
{
class Program
{
private const int sSize = 75; // Population size at start.
private const int mTest = 1000; // Arbitrary number of test cycles.
private const double pMating = 0.7; // Probability of two chromosomes mating. Range: 0.0 < MATING_PROBABILITY < 1.0
private const double rMutation = 0.001; // Mutation Rate. Range: 0.0 < MUTATION_RATE < 1.0
private const int minS = 10; // Minimum parents allowed for selection.
private const int MaxS = 50; // Maximum parents allowed for selection. Range: MIN_SELECT < MAX_SELECT < START_SIZE
private const int offSpring = 20; // New offspring created per generation. Range: 0 < OFFSPRING_PER_GENERATION < MAX_SELECT.
private const int minRandom = 8; // For randomizing starting chromosomes
private const int maxShuffles = 20;
private const int maxPBC = 4; // Maximum Position-Based Crossover points. Range: 0 < PBC_MAX < 8 (> 8 isn't good).
private const int maxLength = 10; // chess board width.
private static int epoch = 0;
private static int childCount = 0;
private static int nextMutation = 0; // For scheduling mutations.
private static int mutations = 0;
private static List<Chromosome> population = new List<Chromosome>();
private static void algorithm()
{
int popSize = 0;
Chromosome thisChromo = null;
bool done = false;
initializeChromosomes();
mutations = 0;
nextMutation = getRandomNumber(0, (int)Math.Round(1.0 / rMutation));
while (!done)
{
popSize = population.Count;
for (int i = 0; i < popSize; i++)
{
thisChromo = population[i];
if ((thisChromo.conflicts() == 0) || epoch == mTest)
{
done = true;
}
}
getFitness();
rouletteSelection();
mating();
prepNextEpoch();
epoch++;
// This is here simply to show the runtime status.
Console.WriteLine("Epoch: " + epoch);
}
Console.WriteLine("done.");
if (epoch != rMutation)
{
popSize = population.Count;
for (int i = 0; i < popSize; i++)
{
thisChromo = population[i];
if (thisChromo.conflicts() == 0)
{
printSolution(thisChromo);
}
}
}
Console.WriteLine("Completed " + epoch + " epochs.");
Console.WriteLine("Encountered " + mutations + " mutations in " + childCount + " offspring.");
return;
}
private static void getFitness()
{
// Lowest errors = 100%, Highest errors = 0%
int popSize = population.Count;
Chromosome thisChromo = null;
double bestScore = 0;
double worstScore = 0;
// The worst score would be the one with the highest energy, best would be lowest.
worstScore = population[maximum()].conflicts();
// Convert to a weighted percentage.
bestScore = worstScore - population[minimum()].conflicts();
for (int i = 0; i < popSize; i++)
{
thisChromo = population[i];
thisChromo.fitness((worstScore - thisChromo.conflicts()) * 100.0 / bestScore);
}
return;
}
private static void rouletteSelection()
{
int j = 0;
int popSize = population.Count;
double genT = 0.0;
double selT = 0.0;
int maximumToSelect = getRandomNumber(minS, MaxS);
double rouletteSpin = 0.0;
Chromosome thisChromo = null;
Chromosome thatChromo = null;
bool done = false;
for (int i = 0; i < popSize; i++)
{
thisChromo = population[i];
genT += thisChromo.fitness();
}
genT *= 0.01;
for (int i = 0; i < popSize; i++)
{
thisChromo = population[i];
thisChromo.selectionProbability(thisChromo.fitness() / genT);
}
for (int i = 0; i < maximumToSelect; i++)
{
rouletteSpin = getRandomNumber(0, 99);
j = 0;
selT = 0;
done = false;
while (!done)
{
thisChromo = population[j];
selT += thisChromo.selectionProbability();
if (selT >= rouletteSpin)
{
if (j == 0)
{
thatChromo = population[j];
}
else if (j >= popSize - 1)
{
thatChromo = population[popSize - 1];
}
else
{
thatChromo = population[j - 1];
}
thatChromo.selected(true);
done = true;
}
else
{
j++;
}
}
}
return;
}
// This is where you can choose between options:
// To choose between crossover options, uncomment one of:
// partiallyMappedCrossover(),
// positionBasedCrossover(), while keeping the other two commented out.
private static void mating()
{
int getRand = 0;
int parentA = 0;
int parentB = 0;
int newIndex1 = 0;
int newIndex2 = 0;
Chromosome newChromo1 = null;
Chromosome newChromo2 = null;
for (int i = 0; i < offSpring; i++)
{
parentA = chooseParent();
// Test probability of mating.
getRand = getRandomNumber(0, 100);
if (getRand <= pMating * 100)
{
parentB = chooseParent(parentA);
newChromo1 = new Chromosome();
newChromo2 = new Chromosome();
population.Add(newChromo1);
newIndex1 = population.IndexOf(newChromo1);
population.Add(newChromo2);
newIndex2 = population.IndexOf(newChromo2);
// Choose either, or both of these:
partialCrossover(parentA, parentB, newIndex1, newIndex2);
//positionBasedCrossover(parentA, parentB, newIndex1, newIndex2);
if (childCount - 1 == nextMutation)
{
exchangeMutation(newIndex1, 1);
}
else if (childCount == nextMutation)
{
exchangeMutation(newIndex2, 1);
}
population[newIndex1].computeConflicts();
population[newIndex2].computeConflicts();
childCount += 2;
// Schedule next mutation.
if (childCount % (int)Math.Round(1.0 / rMutation) == 0)
{
nextMutation = childCount + getRandomNumber(0, (int)Math.Round(1.0 / rMutation));
}
}
} // i
return;
}
private static void partialCrossover(int chromA, int chromB, int child1, int child2)
{
int j = 0;
int item1 = 0;
int item2 = 0;
int pos1 = 0;
int pos2 = 0;
Chromosome thisChromo = population[chromA];
Chromosome thatChromo = population[chromB];
Chromosome newChromo1 = population[child1];
Chromosome newChromo2 = population[child2];
int crossPoint1 = getRandomNumber(0, maxLength - 1);
int crossPoint2 = getExclusiveRandomNumber(maxLength - 1, crossPoint1);
if (crossPoint2 < crossPoint1)
{
j = crossPoint1;
crossPoint1 = crossPoint2;
crossPoint2 = j;
}
// Copy Parent genes to offspring.
for (int i = 0; i < maxLength; i++)
{
newChromo1.data(i, thisChromo.data(i));
newChromo2.data(i, thatChromo.data(i));
}
for (int i = crossPoint1; i <= crossPoint2; i++)
{
// Get the two items to swap.
item1 = thisChromo.data(i);
item2 = thatChromo.data(i);
// Get the items// positions in the offspring.
for (j = 0; j < maxLength; j++)
{
if (newChromo1.data(j) == item1)
{
pos1 = j;
}
else if (newChromo1.data(j) == item2)
{
pos2 = j;
}
} // j
// Swap them.
if (item1 != item2)
{
newChromo1.data(pos1, item2);
newChromo1.data(pos2, item1);
}
// Get the items// positions in the offspring.
for (j = 0; j < maxLength; j++)
{
if (newChromo2.data(j) == item2)
{
pos1 = j;
}
else if (newChromo2.data(j) == item1)
{
pos2 = j;
}
} // j
// Swap them.
if (item1 != item2)
{
newChromo2.data(pos1, item1);
newChromo2.data(pos2, item2);
}
} // i
return;
}
private static void positionCrossover(int chromA, int chromB, int child1, int child2)
{
int k = 0;
int numPoints = 0;
int[] tempArray1 = new int[maxLength];
int[] tempArray2 = new int[maxLength];
bool matchFound = false;
Chromosome thisChromo = population[chromA];
Chromosome thatChromo = population[chromB];
Chromosome newChromo1 = population[child1];
Chromosome newChromo2 = population[child2];
// Choose and sort the crosspoints.
numPoints = getRandomNumber(0, maxPBC);
int[] crossPoints = new int[numPoints];
int negativeNancy = -1;
for (int i = 0; i < numPoints; i++)
{
crossPoints[i] = getRandomNumber(0, maxLength - negativeNancy, crossPoints);
} // i
// Get non-chosens from parent 2
k = 0;
for (int i = 0; i < maxLength; i++)
{
matchFound = false;
for (int j = 0; j < numPoints; j++)
{
if (thatChromo.data(i) == thisChromo.data(crossPoints[j]))
{
matchFound = true;
}
} // j
if (matchFound == false)
{
tempArray1[k] = thatChromo.data(i);
k++;
}
} // i
// Insert chosens into child 1.
for (int i = 0; i < numPoints; i++)
{
newChromo1.data(crossPoints[i], thisChromo.data(crossPoints[i]));
}
// Fill in non-chosens to child 1.
k = 0;
for (int i = 0; i < maxLength; i++)
{
matchFound = false;
for (int j = 0; j < numPoints; j++)
{
if (i == crossPoints[j])
{
matchFound = true;
}
} // j
if (matchFound == false)
{
newChromo1.data(i, tempArray1[k]);
k++;
}
} // i
// Get non-chosens from parent 1
k = 0;
for (int i = 0; i < maxLength; i++)
{
matchFound = false;
for (int j = 0; j < numPoints; j++)
{
if (thisChromo.data(i) == thatChromo.data(crossPoints[j]))
{
matchFound = true;
}
} // j
if (matchFound == false)
{
tempArray2[k] = thisChromo.data(i);
k++;
}
} // i
// Insert chosens into child 2.
for (int i = 0; i < numPoints; i++)
{
newChromo2.data(crossPoints[i], thatChromo.data(crossPoints[i]));
}
// Fill in non-chosens to child 2.
k = 0;
for (int i = 0; i < maxLength; i++)
{
matchFound = false;
for (int j = 0; j < numPoints; j++)
{
if (i == crossPoints[j])
{
matchFound = true;
}
} // j
if (matchFound == false)
{
newChromo2.data(i, tempArray2[k]);
k++;
}
} // i
return;
}
private static void exchangeMutation(int index, int exchanges)
{
int i = 0;
int tempData = 0;
Chromosome thisChromo = null;
int gene1 = 0;
int gene2 = 0;
bool done = false;
thisChromo = population[index];
while (!done)
{
gene1 = getRandomNumber(0, maxLength - 1);
gene2 = getExclusiveRandomNumber(maxLength - 1, gene1);
// Exchange the chosen genes.
tempData = thisChromo.data(gene1);
thisChromo.data(gene1, thisChromo.data(gene2));
thisChromo.data(gene2, tempData);
if (i == exchanges)
{
done = true;
}
i++;
}
mutations++;
return;
}
private static int chooseParent()
{
// Overloaded function, see also "chooseparent(ByVal parentA As Integer)".
int parent = 0;
Chromosome thisChromo = null;
bool done = false;
while (!done)
{
// Randomly choose an eligible parent.
parent = getRandomNumber(0, population.Count - 1);
thisChromo = population[parent];
if (thisChromo.selected() == true)
{
done = true;
}
}
return parent;
}
{
// Overloaded function, see also "chooseparent()".
int parent = 0;
Chromosome thisChromo = null;
bool done = false;
while (!done)
{
// Randomly choose an eligible parent.
parent = getRandomNumber(0, population.Count - 1);
if (parent != parentA)
{
thisChromo = population[parent];
if (thisChromo.selected() == true)
{
done = true;
}
}
}
return parent;
}
private static void prepNextEpoch()
{
int popSize = 0;
Chromosome thisChromo = null;
// Reset flags for selected individuals.
popSize = population.Count;
for (int i = 0; i < popSize; i++)
{
thisChromo = population[i];
thisChromo.selected(false);
}
return;
}
private static void printSolution(Chromosome bestSolution)
{
string[][] board = RectangularArrays.ReturnRectangularStringArray(maxLength, maxLength);
// Clear the board.
for (int x = 0; x < maxLength; x++)
{
for (int y = 0; y < maxLength; y++)
{
board[x][y] = "";
}
}
for (int x = 0; x < maxLength; x++)
{
board[x][bestSolution.data(x)] = "Q";
}
// Display the board.
Console.WriteLine("Board:");
for (int y = 0; y < maxLength; y++)
{
for (int x = 0; x < maxLength; x++)
{
if (string.ReferenceEquals(board[x][y], "Q"))
{
Console.Write("Q ");
}
else
{
Console.Write(". ");
}
}
Console.Write("\n");
}
return;
}
private static int getRandomNumber(int low, int high)
{
return (int)Math.Round((high - low) * (new Random()).NextDouble() + low);
}
private static int getExclusiveRandomNumber(int high, int except)
{
bool done = false;
int getRand = 0;
while (!done)
{
getRand = (new Random()).Next(high);
if (getRand != except)
{
done = true;
}
}
return getRand;
}
private static int getRandomNumber(int low, int high, int[] except)
{
bool done = false;
int getRand = 0;
if (high != low)
{
while (!done)
{
done = true;
getRand = (int)Math.Round((high - low) * (new Random()).NextDouble() + low);
for (int i = 0; i < except.Length; i++) //UBound(except)
{
if (getRand == except[i])
{
done = false;
}
} // i
}
return getRand;
}
else
{
return high; // or low (it doesn't matter).
}
}
private static int minimum()
{
// Returns an array index.
int popSize = 0;
Chromosome thisChromo = null;
Chromosome thatChromo = null;
int winner = 0;
bool foundNewWinner = false;
bool done = false;
while (!done)
{
foundNewWinner = false;
popSize = population.Count;
for (int i = 0; i < popSize; i++)
{
if (i != winner)
{ // Avoid self-comparison.
thisChromo = population[i];
thatChromo = population[winner];
if (thisChromo.conflicts() < thatChromo.conflicts())
{
winner = i;
foundNewWinner = true;
}
}
}
if (foundNewWinner == false)
{
done = true;
}
}
return winner;
}
private static int maximum()
{
// Returns an array index.
int popSize = 0;
Chromosome thisChromo = null;
Chromosome thatChromo = null;
int winner = 0;
bool foundNewWinner = false;
bool done = false;
while (!done)
{
foundNewWinner = false;
popSize = population.Count;
for (int i = 0; i < popSize; i++)
{
if (i != winner)
{ // Avoid self-comparison.
thisChromo = population[i];
thatChromo = population[winner];
if (thisChromo.conflicts() > thatChromo.conflicts())
{
winner = i;
foundNewWinner = true;
}
}
}
if (foundNewWinner == false)
{
done = true;
}
}
return winner;
}
private static void initializeChromosomes()
{
int shuffles = 0;
Chromosome newChromo = null;
int chromoIndex = 0;
for (int i = 0; i < sSize; i++)
{
newChromo = new Chromosome();
population.Add(newChromo);
chromoIndex = population.IndexOf(newChromo);
// Randomly choose the number of shuffles to perform.
shuffles = getRandomNumber(minRandom, maxShuffles);
exchangeMutation(chromoIndex, shuffles);
population[chromoIndex].computeConflicts();
}
return;
}
private class Chromosome
{
internal int[] mData = new int[maxLength];
internal double mFitness = 0.0;
internal bool mSelected = false;
internal double mSelectionProbability = 0.0;
internal int mConflicts = 0;
public Chromosome()
{
for (int i = 0; i < maxLength; i++)
{
this.mData[i] = i;
}
return;
}
public virtual void computeConflicts()
{
int x = 0;
int y = 0;
int tempx = 0;
int tempy = 0;
//string[][] board = new string[MAX_LENGTH][MAX_LENGTH];
string[][] board = RectangularArrays.ReturnRectangularStringArray(maxLength, maxLength);
int conflicts = 0;
int[] dx = new int[] { -1, 1, -1, 1 };
int[] dy = new int[] { -1, 1, 1, -1 };
bool done = false;
// Clear the board.
for (int i = 0; i < maxLength; i++)
{
for (int j = 0; j < maxLength; j++)
{
board[i][j] = "";
}
}
for (int i = 0; i < maxLength; i++)
{
board[i][this.mData[i]] = "Q";
}
// Walk through each of the Queens and compute the number of conflicts.
for (int i = 0; i < maxLength; i++)
{
x = i;
y = this.mData[i];
// Check diagonals.
for (int j = 0; j <= 3; j++)
{
tempx = x;
tempy = y;
done = false;
while (!done)
{
tempx += dx[j];
tempy += dy[j];
if ((tempx < 0 || tempx >= maxLength) || (tempy < 0 || tempy >= maxLength))
{
done = true;
}
else
{
if (board[tempx][tempy].ToString().ToUpper().Equals("Q"))// ignore the case of 2 strings
{
conflicts++;
}
}
}
}
}
this.mConflicts = conflicts;
}
public virtual void conflicts(int value)
{
this.mConflicts = value;
return;
}
public virtual int conflicts()
{
return this.mConflicts;
}
public virtual double selectionProbability()
{
return mSelectionProbability;
}
public virtual void selectionProbability(double SelProb)
{
mSelectionProbability = SelProb;
return;
}
public virtual bool selected()
{
return mSelected;
}
public virtual void selected(bool sValue)
{
mSelected = sValue;
return;
}
public virtual double fitness()
{
return mFitness;
}
public virtual void fitness(double score)
{
mFitness = score;
return;
}
public virtual int data(int index)
{
return mData[index];
}
public virtual void data(int index, int value)
{
mData[index] = value;
return;
}
} // Chromosome
static void Main(string[] args)
{
algorithm();
return;
}
}
}
This is the second code here:
namespace NQueen1
{
internal static class RectangularArrays
{
internal static string[][] ReturnRectangularStringArray(int size1, int size2)
{
string[][] newArray = new string[size1][];
for (int array1 = 0; array1 < size1; array1++)
{
newArray[array1] = new string[size2];
}
return newArray;
}
}
}
THe Error:
Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
at System.Collections.Generic.List`1.get_Item(Int32 index)
at NQueen1.Program.rouletteSelection() in C:\Users\Inspiron\Documents\coid\NQueen1\NQueen1\Program.cs:line 143
at NQueen1.Program.algorithm() in C:\Users\Inspiron\Documents\coid\NQueen1\NQueen1\Program.cs:line 56
at NQueen1.Program.Main(String[] args) in C:\Users\Inspiron\Documents\coid\NQueen1\NQueen1\Program.cs:line 841
I have no clue why its throwing off these errors I tried about almost everything I could think of to fix it
This is just a random guess.
My Spidey Senses tells me thisChromo = population[j] is probably overrunning the size of array, i.e. its in a while loop with j++ and there is no real bounds checking
private static void rouletteSelection()
{
...
for (int i = 0; i < maximumToSelect; i++)
{
...
while (!done)
{
thisChromo = population[j];
...
j++;
If this is the problem, I'd consider the possibility that j will be larger than population.Length and therefore breaking out of the loop; using an if statement; or just refactoring this logic
Tips for your future questions
If you have a runtime error, show us the line of code it has the error on
Pasting code is vital, however pasting too much is annoying and hard to read
If you paste code, at least try to format it
Learn to use the debugger and breakpoints (see: How to use the Debugger, Using Breakpoints).
ok my problem has changed my problem now is that im trying to use the minimax algorithm like that website explains http://neverstopbuilding.com/minimax
and it gives me this error: "Argument out of range exception"
why is it happening i cant tell why the exception happens
this is what i did:
int MiniMax(Seed[,] board, Seed currPlayer)
{
if (checkBoard1(this.board) != -1) return score();
List<int> scores = new List<int>();
List<Vector2> moves = generateMoves();
for (int i = 0; i < moves.Count; i++)
{
if (currPlayer == Seed.NOUGHT)
currPlayer = Seed.CROSS;
else
currPlayer = Seed.NOUGHT;
Seed[,] possibleBoard = getPossibleBoard(moves[i]);
scores.Add(MiniMax(possibleBoard, currPlayer));
}
if(currPlayer == Seed.NOUGHT)
{
int max_score_index = getMaxIndexFromList(scores);
choice = (Vector2)moves[max_score_index];
return scores[max_score_index];
}
else
{
int min_score_index = getMinIndexFromList(scores);
choice = (Vector2)moves[min_score_index];
return scores[min_score_index];
}
}
int getMinIndexFromList(List<int> list)
{
int min = list[0], minIndex = 0;
for (int i = 1; i < list.Count; i++)
{
if (list[i] < min)
{
min = list[i];
minIndex = i;
}
}
return minIndex;
}
Can you guys please help me with basic insertion sorting in C#. I have a list of names and city of residence in a array and need to sort this array by comparing the city of residence. List has to be sorted in alphabetical order. Comparator has been set up and works I'm just kinda lost with the insertion sorter programming as this is the first time we are doing that method of sorting.
Here's what I've tried so far:
public void InsertionSort()
{
for (int i = 0; i < Count; i++)
{
Student cur = Attendees[i];
for (int j = 0; j < Count; j++)
{
Student Sel = Attendees[j];
if (cur.CompareTo(Sel) < 0)
{
Student temp = Attendees[j];
Attendees[j] = Attendees[i];
for (int k = i; k > j; k--)
Attendees[k] = Attendees[k - 1];
Attendees[k + 1] = temp;
}
}
}
}
Try like this...
public void InsertionSort()
{
for (int i = 0; i < Count; i++)
{
int j = i;
While(j > 0)
{
Student cur = Attendees[j];
Student sel = Attendees[j-1];
if (cur.CompareTo(Sel) < 0)
{
Student temp = cur;
cur = sel;
sel = temp;
j--
}
else
break;
}
}
}
public void InsertionSort()
{
for (int i = 1; i < Count; i++) // Iterate beginning at 1, because we assume that 0 is already sorted
{
for (int j = i; j > 0; j--) // Iterate backwards, starting from 'i'
{
Student cur = Attendees[j - 1];
Student tbs = Attendees[j]; // 'tbs' == "to be sorted"
if (cur.CompareTo(tbs) < 0) // usually, classes that implement 'CompareTo()' also implement 'operator <()', 'operator >()' and 'operator ==()', so you could have just written 'cur < tbs'
{
Student temp = Attendees[j];
Attendees[j] = Attendees[j - 1];
Attendees[j - 1] = temp;
}
else
break; // since 'tbs' is no longer > 'cur', it is part of our sorted list. We don't need to sort that particular 'tbs' any further
}
}
}
Keep in mind, that this algorithm sorts your list in descending order.
int[] newarr = {2,1,5,3,7,6};
int a, b;
for (int i = 1; i < newarr.Length; i++)
{
a = newarr[i];
b = i - 1;
while(b>=0 && newarr[b]>a)
{
newarr[b+1] = newarr[b];
b=b-1;
}
newarr[b+1] = a;
}