as all newbies to the searching algorithms, i am working on an example of the old fashion 8-problem puzzle, i have done the breadth first algorithm which is in the code below, and i was wondering how can convert it to the depth first limited search.
how can I convert from the breadth first algorithm to the depth first limited search algorithm??
code :
class BFS
{
int[] GoalState = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
private Queue<Node> Frontier;
private HashSet<Node> Solution;
private Node RootNode;
public BFS(int[] StartState)
{
this.RootNode = new Node(StartState, -1, "\0");
Solution = new HashSet<Node>();
Frontier = new Queue<Node>();
}
public void Solve()
{
Node ActiveNode = RootNode;
bool IsSolved = false;
while (!IsGoalState(ActiveNode.GetState()))
{
Solution.Add(ActiveNode);
foreach (Node successor in GenerateSuccessor(ActiveNode))
{
Frontier.Enqueue(successor);
if (IsGoalState(successor.GetState()))
{
IsSolved = true;
Solution.Add(successor);
break;
}
}
if (IsSolved)
break;
ActiveNode = Frontier.Dequeue();
}
WriteSolution();
}
public IEnumerable<Node> GenerateSuccessor(Node ParentNode)
{
int[] ParentState = ParentNode.GetState();
int EmptySpacePosition = 0;
int temp;
for (int x = 0; x < 9; x++)
{
if (ParentState[x] == 0)
{
EmptySpacePosition = x;
break;
}
}
//Can move empty space to LEFT?
if (EmptySpacePosition != 0 && EmptySpacePosition != 3 && EmptySpacePosition != 6)
{
int[] _State = (int[])ParentState.Clone();
_State[EmptySpacePosition] = _State[EmptySpacePosition - 1];
_State[EmptySpacePosition - 1] = 0;
yield return new Node(_State, ParentNode.GetId(), "Left ");
}
//Can move empty space to RIGHT?
if (EmptySpacePosition != 2 && EmptySpacePosition != 5 && EmptySpacePosition != 8)
{
int[] _State = (int[])ParentState.Clone();
_State[EmptySpacePosition] = _State[EmptySpacePosition + 1];
_State[EmptySpacePosition + 1] = 0;
yield return new Node(_State, ParentNode.GetId(),"Right ");
}
//Can move empty space to UP?
if (EmptySpacePosition > 2)
{
int[] _State = (int[])ParentState.Clone();
_State[EmptySpacePosition] = _State[EmptySpacePosition - 3];
_State[EmptySpacePosition - 3] = 0;
yield return new Node(_State, ParentNode.GetId(), "Up ");
}
//Can move empty space to DOWN?
if (EmptySpacePosition < 6)
{
int[] _State = (int[])ParentState.Clone();
_State[EmptySpacePosition] = _State[EmptySpacePosition + 3];
_State[EmptySpacePosition + 3] = 0;
yield return new Node(_State, ParentNode.GetId(),"Down ");
}
}
public bool IsGoalState(int[] State)
{
for (int x = 0; x < 9; x++)
{
if (State[x] != GoalState[x])
return false;
}
return true;
}
public void WriteSolution()
{
StringBuilder s = new StringBuilder();
int ParentId = 0;
#region InfoPrint
Console.Write("Puzzle= ");
foreach (int i in RootNode.GetState())
{
Console.Write(i);
}
Console.WriteLine();
Console.WriteLine("Nodes Generated= " + (Solution.Count + Frontier.Count));
#endregion
foreach (Node n in Solution.Reverse())
{
if (ParentId == 0 || n.GetId() == ParentId)
{
s.Append(n.GetMove());
ParentId = n.GetParentId();
}
}
Console.WriteLine("Solution Length= " + (s.Length - 1));
Console.WriteLine("Solution= " + s.ToString());
}
}
and here is my class node
class Node
{
static int _IdCnt = 0;
private int[] State;
private int Id;
private int ParentId;
private string Move;
public Node(int[] State, int ParentId, string Move)
{
Id = _IdCnt++;
this.State = State;
this.ParentId = ParentId;
this.Move = Move;
}
public void SetState(int[] State)
{
this.State = State;
}
public int[] GetState()
{
return (int[])State.Clone();
}
public int GetId()
{
return Id;
}
public int GetParentId()
{
return ParentId;
}
public string GetMove()
{
return Move;
}
}
In the DFS, you'll need to use stack instead of queue. Basically, you add the root node to a stack, and while stack contains a node, you pop the node, do your logic, add its neighbors to the stack and continue.
1. Add root to a stack.
2. while(stack.Count > 0)
{
3. pop the stack
4. if matches, return
5. else add neighbors to stack
}
return not found
Related
I wrote a simple implementation of a b-tree, and the problem is that it is too slow (tl9 on codeforces). What should i change to speed up this tree?
The memory limit problem can be easily fixed by increasing the constant b, but then there are time limit problems.
class BtreeSimple
{
public Bnode root = new Bnode(true);
private static int counter;
public void Add(int key)
{
var (overkey, overflow, overvalue) = root.Insert(key, counter);
counter++;
if (overflow == null)
return;
root = new Bnode(false) {Count = 1, Keys = {[0] = overkey}, Vals = {[0] = overvalue}, Kids = {[0] = root, [1] = overflow}};
}
}
class Bnode
{
const int b = 16;
public int Count;
public int[] Keys = new int[2 * b + 1];
public Bnode[] Kids;
public Bnode(bool leaf) => Kids = leaf ? null : new Bnode[2 * b + 2];
public int[] Vals = new int[2 * b + 1];
public (int, Bnode, int) Insert(int key, int value)
{
var i = GetKeyPosition(key);
if (Kids == null) return InsertAt(i, key, null, value);
var (overkey, overflow, overvalue) = Kids[i].Insert(key, value);
return overflow == null ? (0, null, 0) : InsertAt(i, overkey, overflow, overvalue);
}
private int GetKeyPosition(int key)
{
var i = 0;
while (i < Count && Keys[i] < key)
i++;
return i;
}
private (int, Bnode, int) InsertAt(int i, int key, Bnode keyNode, int value)
{
Array.Copy(Keys, i, Keys, i + 1, Count - i);
Keys[i] = key;
Vals[i] = value;
if (keyNode != null)
{
Array.Copy(Kids, i + 1, Kids, i + 2, Count - i);
Kids[i + 1] = keyNode;
}
return ++Count <= 2 * b ? (0, null, 0) : Split();
}
private (int, Bnode, int) Split()
{
var split = new Bnode(Kids == null) { Count = b };
Array.Copy(Keys, b + 1, split.Keys, 0, b);
Array.Copy(Vals, b + 1, split.Vals, 0, b);
if (Kids != null)
Array.Copy(Kids, b + 1, split.Kids, 0, b + 1);
Count = b;
return (Keys[b], split, Vals[b]);
}
public int FindNearest(int key)
{
var i = GetKeyPosition(key);
if (Keys[i] == key)
return Vals[i];
if (Kids != null)
return Kids[i].FindNearest(key);
if (i >= Count)
return Vals[i - 1]+1;
if (Keys[i] < key)
return Vals[i] + 1;
return Vals[i];
}
}
We have a sorted array (for example arr = [8, 9, 10, 11, 15, 17, 20]) and keys (for example keys = [7, 10, 21, 20]). The task is to tell how many keys from arr are less than keys[i] for each i. For this purpose I made a methdod "FindNearest".
Everything else in the code is just pure b-tree.
I'm trying to compile the below code: (normally get and set operation)
please assist with reviewing the insertion sort function, all the rest compiling perfectly.
The return value comparing 2 cells only (and it's correct).
any idea what can cause that?
private static void Main()
{
IArray<int?> arr = Read();
Console.WriteLine(arr);
SelectionSort(arr);
Console.WriteLine(arr);
if (arr.Length >= 2)
{
arr.Set(arr.Length - 2, null);
Console.WriteLine(arr);
}
if (arr.Length >= 1)
{
arr.Set(arr.Length - 1, null);
Console.WriteLine(arr);
}
SelectionSort(arr);
Console.WriteLine(arr);
Console.WriteLine("(" + arr.Get(100) + ")");
Console.WriteLine("insertion sort");
int n = arr.Length;
Insertionsort(arr, n);
Console.WriteLine(arr);
//// throw exception
//_ = new DynArr<int>();
}
private static IArray<int?> Read()
{
var arr = new DynArr<int?>();
Console.Write("Enter size >> ");
var size = int.Parse(Console.ReadLine().Trim());
for (var i = 0; i < size; ++i)
{
Console.Write("Enter [" + i + "] >> ");
arr.Set(i, int.Parse(Console.ReadLine().Trim()));
}
return arr;
}
}
private static void Insertionsort(IArray<int?> arr, int n)
{
for (int i = 1; i < n; i++)
{
var j = i - 1;
voidcompare(arr, i, j);
}
}
private static void voidcompare(IArray<int?> arr, int i, int j)
{
var c = arr.Get(i);
while (j >= 0 && arr.Get(j) > c)
{
arr.Set(j + 1, c);
}
}
}
}
Your Sort alg. isn't corect. See hier how it's working - Insertion Sort. Bellow i provide you a possible implementation.
public class Program
{
static void Main()
{
var collection = new List<int?> { 25, 71, 43, -1, 15, 0, 38 };
DoInsertionSort(collection, collection.Count);
Console.WriteLine(string.Join(Environment.NewLine, collection));
}
static void DoInsertionSort(IList<int?> collection, int length)
{
if (collection is null || collection.Count == 0 || length <= 0 || length > collection.Count)
{
return;
}
var previous = default(int?);
for (int index = 0; index < length; index++)
{
var current = collection.Get(index);
if (current < previous)
{
SwapUpToStart(collection, current, index);
}
previous = collection.Get(index);
}
}
private static void SwapUpToStart(IList<int?> collection, int? current, int currentIndex)
{
for (int index = currentIndex - 1; index >= 0; index--)
{
var previous = collection.Get(index);
if (current >= previous)
{
break;
}
collection.Swap(index, current, previous);
}
}
}
public static class YourIArray_T_Implementation
{
public static int? Get(this IList<int?> collection, int index)
{
return collection[index];
}
public static void Swap(this IList<int?> collection, int index, int? current, int? previous)
{
collection[index] = current;
collection[index + 1] = previous;
}
}
I'm trying to come up with my "own" a* pathfinding algorithm following the explanation of this article : https://www.redblobgames.com/pathfinding/a-star/introduction.html
But it seems that my pathfinding code runs into some sort of infinte-while-loop which inmediatly crashes Unity. But I honestly do not know what am I doing wrong
Here's my code
EDIT : it seems that unity editor crashes due to an OutOfMemory exception. I do not know what is going on
public class PathFinding {
List<PathNode> openList;
List<PathNode> closedList;
Grid_Ian<PathNode> grid;
public PathFinding(Grid_Ian<PathNode> grid)
{
openList = new List<PathNode>();
closedList = new List<PathNode>();
this.grid = grid;
}
public List<PathNode> makePath(PathNode startNode, PathNode endNode)
{
if (startNode == null || endNode == null)
{
return new List<PathNode>();
}
if(grid.getGridObject(startNode.x,startNode.y) == null
|| grid.getGridObject(endNode.x, endNode.y) == null)
{
return new List<PathNode>();
}
startNode.hCost = calculateDistanceCost(startNode, endNode);
startNode.gCost = 0;
startNode.calculateFCost();
startNode.cameFrom = null;
openList.Add(startNode);
PathNode currentNode = startNode;
while (openList.Count > 0)
{
Debug.Log("LOOPING");
currentNode = getLowestFcost(openList);
openList.Remove(currentNode);
closedList.Add(currentNode);
if (currentNode.x == endNode.x &&
currentNode.y == endNode.y)
{
return getPath(currentNode);
}
foreach (PathNode next in getNeighbors(currentNode))
{
int newCost = currentNode.fCost + calculateDistanceCost(currentNode, next);
if (closedList.Contains(next)) continue;
if (next.cameFrom == null || newCost < next.fCost)
{
Debug.Log("NUEVO VECINO");
int nextCost = calculateDistanceCost(currentNode, next);
next.gCost = currentNode.gCost + nextCost;
next.hCost = currentNode.hCost + nextCost;
next.calculateFCost();
next.cameFrom = currentNode;
openList.Add(next);
}
}
}
return new List<PathNode>();
}
public List<PathNode> getNeighbors(PathNode currentNode)
{
List<PathNode> neighborNodes = new List<PathNode>();
if (currentNode.x - 1 >= 0)
{
//left
neighborNodes.Add(getNode(currentNode.x - 1, currentNode.y));
}
if (currentNode.x + 1 >= 0)
{
//right
neighborNodes.Add(getNode(currentNode.x + 1, currentNode.y));
}
//up
if (currentNode.y + 1 >= 0)
{
neighborNodes.Add(getNode(currentNode.x, currentNode.y + 1));
}
//down
if (currentNode.y - 1 >= 0)
{
neighborNodes.Add(getNode(currentNode.x, currentNode.y - 1));
}
return neighborNodes;
}
public PathNode getNode(int x, int y)
{
if(grid.getGridObject(x,y) == null)
{
}
return grid.getGridObject(x, y);
}
private PathNode getLowestFcost(List<PathNode> nodeList)
{
PathNode lowestNode = getNode(0,0); // TODO : ARREGLAR
int fCost = 0;
foreach (PathNode node in nodeList)
{
if (fCost > node.fCost)
{
fCost = node.fCost;
lowestNode = node;
}
}
return lowestNode;
}
private int calculateDistanceCost(PathNode a, PathNode b)
{
return Mathf.Abs(a.x - b.x) + Mathf.Abs(a.y - b.y);
}
private List<PathNode> getPath(PathNode currentNode ){
List<PathNode> path = new List<PathNode>();
path.Add(currentNode);
while (currentNode.cameFrom != null)
{
currentNode = currentNode.cameFrom;
path.Add(currentNode);
}
path.Reverse();
return path;
}
public void getXY(Vector3 worldPosition, out int x, out int y)
{
grid.GetXY(worldPosition, out x, out y);
}
}
public class PathNode {
public int x, y;
public int hCost, gCost,fCost;
public PathNode cameFrom;
// G = start
// H = end
// F = G + H
public PathNode(int x,int y)
{
this.x = x;
this.y = y;
}
public void calculateFCost()
{
fCost = hCost + gCost;
}
}
I tried to check your Code with my and 2 Ideas you could try.
First is I think you shouldn't set the in the foreach the newCost before the if. So you could try:
foreach (PathNode next in getNeighbors(currentNode))
{
if (closedList.Contains(next)) continue;
int newCost = currentNode.fCost + calculateDistanceCost(currentNode, next);
if (next.cameFrom == null || newCost < next.fCost)
{
Debug.Log("NUEVO VECINO");
int nextCost = calculateDistanceCost(currentNode, next);
next.gCost = currentNode.gCost + nextCost;
next.hCost = currentNode.hCost + nextCost;
next.calculateFCost();
next.cameFrom = currentNode;
openList.Add(next);
}
}
Or one more thing. I have for some Reasons again a openList.Contains check before I add it to the openList. I do not know why again I did this but I think maybe you can try it, don't know if this helps. I made it quite a long time ago:
foreach (PathNode next in getNeighbors(currentNode))
{
int newCost = currentNode.fCost + calculateDistanceCost(currentNode, next);
if (closedList.Contains(next)) continue;
if (next.cameFrom == null || newCost < next.fCost)
{
Debug.Log("NUEVO VECINO");
int nextCost = calculateDistanceCost(currentNode, next);
next.gCost = currentNode.gCost + nextCost;
next.hCost = currentNode.hCost + nextCost;
next.calculateFCost();
next.cameFrom = currentNode;
if(!openList.Contains(next))
{
openList.Add(next);
}
}
}
I found two more things.
First your getNode function shouldn't look like this:
public PathNode getNode(int x, int y)
{
if(grid.getGridObject(x,y) == null)
{
}
return grid.getGridObject(x, y);
}
It should be:
public PathNode getNode(int x, int y)
{
if(grid.getGridObject(x,y) != null)
{
return grid.getGridObject(x, y);
}
return null; //need error handling
}
And the Second thing is for your getNeighbors. I do not know exactly how you create the Nodes, but for example they are in a Grid you should check if there is something for X and Y and not OutOfIndex.
Here my check out of my Code for one NeighborNode:
if (checkX >= 0 && checkX < gridSizeX)
{
if (checkY >= 0 && checkY < gridSizeY)
{
neighborList.Add(nodeArray[checkX, checkY]);
}
}
Because of getNode function you add to the openList NULL
I am trying for the last few hours on how to parse a string with algebric notation.
For example if I have the input:
X+8X-21X+21X+16
The output should be:
9X+16
so far if I tried to see if there exists a number behind X and tried many cases, however I keep on getting an index out of bounds error, and rightufully so. Any suggestions on how to fix it?
int getXPosition= LHSString.IndexOf("X");
int noOfXs = LHSString.Split('X').Length - 1;
int XCount = 0;
if (getXPosition > -1)
{
while (XCount <= noOfXs)
{
int posX = getPositionX(s);
Regex noBeforeX = new Regex(#"\d+");
if ((posX - 1) > -1 && noBeforeX.IsMatch(LHSString.Substring(posX-1,1)))
{
string getNumber = LHSString.Substring(posX-1, 1);
sum += Convert.ToInt32(getNumber);
}
if ((posX - 2) > -1 && noBeforeX.IsMatch(LHSString.Substring(posX - 2, 1)))
{
string gotNumber = LHSString.Substring(posX - 1, 1);
int Number=Convert.ToInt32(gotNumber);
sum += Number;
}
XCount++;
s = s.Substring(posX + 1);
}
}
I would use a more maintainable approach. separate different code parts and use collection of class that will represent the "part" in the algebraic equation.
here is my suggestion:
class Program
{
static void Main(string[] args)
{
string[] operators = { "+", "-", "/", "*" };
string test = "X+8X-21X+21X+16";
int locationcounter = 0;
string part = string.Empty;
List<Part> partsList = new List<Part>();
for (int i = 0; i < test.Length; i++)
{
if (operators.Contains(test[i].ToString()))
{
var operatorbeofore = (partsList.Count <= 0 ? "" : partsList[partsList.Count - 1].OperatorAfter);
partsList.Add(new Part(part, operatorbeofore, test[i].ToString(), locationcounter));
locationcounter++;
part = string.Empty;
}
else
{
part += test[i].ToString();
}
}
// last part that remain
if (part != string.Empty)
{
partsList.Add(new Part(part, partsList[partsList.Count() - 1].OperatorAfter, "", locationcounter++));
}
// output
Console.WriteLine(GetResultOutput(partsList));
Console.ReadLine();
}
private static string GetResultOutput(List<Part> algebraicexpression)
{
// reduce all vars
var vars = algebraicexpression.Where(x => x.IsVar).OrderBy(x => x.locationInEqution).ToList();
int lastVarResult = 0;
int varResult = 0;
if (vars.Count() > 1)
{
lastVarResult = GetCalculation(vars[0].Value, vars[1].Value, vars[1].OperatorBefore);
for (int i = 2; i < vars.Count(); i++)
{
varResult = GetCalculation(lastVarResult, vars[i].Value, vars[i].OperatorBefore);
lastVarResult = varResult;
}
}
else if (vars.Count() == 1)
{
lastVarResult = vars[0].Value;
}
// calculate all "free" numbers
var numbers = algebraicexpression.Where(x => x.IsVar == false).OrderBy(x => x.locationInEqution).ToList();
int lastResult = 0;
int Result = 0;
if (numbers.Count() > 1)
{
lastResult = GetCalculation(vars[0].Value, vars[1].Value, vars[1].OperatorBefore);
for (int i = 2; i < vars.Count(); i++)
{
Result = GetCalculation(lastResult, vars[i].Value, vars[i].OperatorBefore);
lastResult = varResult;
}
}
else if (numbers.Count() == 1)
{
Result = numbers[0].Value;
}
string stringresult = string.Empty;
if (varResult != 0)
{
stringresult = varResult.ToString() + vars[0].Notation;
}
if (Result > 0)
{
stringresult = stringresult + "+" + Result.ToString();
}
else if (Result < 0)
{
stringresult = stringresult + "-" + Result.ToString();
}
return stringresult;
}
private static int GetCalculation(int x, int y, string eqoperator)
{
if (eqoperator == "+")
{
return x + y;
}
else if (eqoperator == "-")
{
return x - y;
}
else if (eqoperator == "*")
{
return x * y;
}
else if (eqoperator == "/")
{
return x / y;
}
else
{
return 0;
}
}
}
class Part
{
public string MyAlgebricPart;
public string OperatorBefore;
public string OperatorAfter;
public int locationInEqution;
public Part(string part, string operatorbefore, string operatorafter, int location)
{
this.MyAlgebricPart = part;
this.OperatorAfter = operatorafter;
this.OperatorBefore = operatorbefore;
this.locationInEqution = location;
}
public int Value
{
get
{
if (MyAlgebricPart.Count() == 1 && Notation != string.Empty)
{
return 1;
}
else
{
string result = new String(MyAlgebricPart.Where(Char.IsDigit).ToArray());
return Convert.ToInt32(result);
}
}
}
public string Notation
{
get
{
var onlyLetters = new String(MyAlgebricPart.Where(Char.IsLetter).ToArray());
if (onlyLetters != "")
{
return onlyLetters[0].ToString();
}
else
{
return string.Empty;
}
}
}
public bool IsVar
{
get
{
if (Notation == string.Empty)
return false;
else
return true;
}
}
}
I'm trying to check if two words are anagram and trying to do this with LinkedList.To do that,first,I created a class named LinkedList:
class LinkedList
{
private Node head;
private int count;
public LinkedList()
{
this.head = null;
this.count = 0;
}
public bool Empty
{
get { return this.count == 0; }
}
public int Count
{
get { return this.count; }
}
public object this[int index]
{
get { return this.Get(index); }
}
public object Add(int index,object o)
{
if (index < 0)
{
throw new ArgumentOutOfRangeException("Index - " + index); //if index is less than 0 throw an error message
}
if (index > count) // if size exceeds the limit of the list the item will be added to the last line of the list.
{
index = count;
}
Node current = this.head;
if(this.Empty || index== 0)
{
this.head = new Node(o, this.head);
}
else
{
for(int i = 0; i < index - 1; i++)
{
current = current.Next;
}
current.Next = new Node(o, current.Next);
}
count++;
return o;
}
public object Add(Object o)
{
return this.Add(count, o);
}
public object Remove(int index)
{
if (index < 0)
{
throw new ArgumentOutOfRangeException("Index - " + index);
}
if (this.Empty)
{
return null;
}
if (index >= this.count)
{
index = count-1;
}
Node current = this.head;
object result = null;
if (index == 0)
{
result = current.Data; //gets the first node
this.head = current.Next; //makes 2nd node to the first node
}
else
{
for(int i = 0; i < index - 1; i++)
{
result = current.Next.Data;
}
result = current.Next;
current.Next = current.Next.Next;
}
count--;
return result;
}
public int IndexOf(object o)
{
Node current = this.head;
for(int i = 0; i < this.count; i++)
{
if (current.Data.Equals(o))
{
return i;
}
current = current.Next;
}
return -1;
}
public bool Contains(object o)
{
return this.IndexOf(o) >= 0; //if list contains object it returns bigger value than -1 and also 0.
}
public object Get(int index)
{
if(index < 0)
{
throw new ArgumentOutOfRangeException("Index - " + index);
}
if (this.Empty)
{
return null;
}
if(index >= this.count)
{
index = this.count-1;
}
Node current = this.head;
for(int i=0;i< index; i++)
{
current = current.Next;
}
return current.Data;
}
}
And another class named "Node":
class Node
{
private object data;
private Node next;
public Node(object data,Node next) //constructor
{
this.data = data;
this.next = next;
}
public object Data
{
get { return this.data; }
set { this.data = value; }
}
public Node Next
{
get { return this.next; }
set { this.next = value; }
}
}
And in main program,I created two objects from linkedlist class and read two strings from user and added the words' chars to the linked list.And compared the chars and if they found they'll be deleted from linkedlist,increases the counter and so on.If counter equals to the list1's number ofelements then they are anagrams if not the words are not anagrams.Here's my main program code:
class Program
{
static void Main(string[] args)
{
int counter = 0;
String word1, word2;
Console.WriteLine("Welcome to Anagram Checker!\nPlease enter your first word:");
word1 = Console.ReadLine();
Console.WriteLine("\nPlease enter the second word:");
word2 = Console.ReadLine();
int result = AnagramChecker(word1, word2, counter);
if (result == 1)
{
Console.WriteLine("These words are anagram");
}
if (result == 0)
{
Console.WriteLine("The words are not anagrams");
}
Console.ReadLine();
}
public static int AnagramChecker(String word1, String word2, int counter)
{
char[] ArrayWord1 = word1.ToCharArray();
char[] ArrayWord2 = word2.ToCharArray();
LinkedList list1 = new LinkedList();
LinkedList list2 = new LinkedList();
for (int i = 0; i < ArrayWord1.Length; i++) //Adds char of word1 to the list
{
list1.Add(i,ArrayWord1[i]);
}
for (int j = 0; j < ArrayWord2.Length; j++) //Adds char of word2 to the list
{
list2.Add(j,ArrayWord2[j]);
}
int max;
if (list1.Count >= list2.Count)
{
max = list1.Count;
}
if (list2.Count > list1.Count)
{
max = list2.Count;
}
for (int i = 0; i < list1.Count; i++)
{
if (list2.Contains(list1[i]) && list1.Contains(list2[i]))
{
list1.Remove(i);
list2.Remove(list2.IndexOf(list1[i]));
counter++;
}
}
Console.WriteLine(counter);
if (counter == word1.Length || counter == word2.Length)
{
return 1;
}
else
return 0;
}
}
When I'm entering different words I get different results.The output examples are below.What do I do wrong?
Outputs:
1-)
2-)
Thanks for your kind helps.
If you're just looking to find if words are anagrams, you can use this method:
private static bool areAnagrams(string word1, string word2)
{
List<char> w1 = word1.OrderBy(c => c).ToList();
List<char> w2 = word2.OrderBy(c => c).ToList();
return !w1.Where((t, i) => t != w2[i]).Any();
}
Which create two lists ordered with the words chars, then compare both.
More readable equivalent:
private static bool areAnagrams(string word1, string word2)
{
List<char> w1 = word1.OrderBy(c => c).ToList();
List<char> w2 = word2.OrderBy(c => c).ToList();
if (w1.Count != w2.Count)
return false;
for (int i = 0; i < w1.Count; i++)
{
if (w1[i] != w2[i])
return false;
}
return true;
}
I fixed the problem,I just modified the if statement which checks if they're anagram or not:
for (int i = 0; i < list1.Count; i++)
{
if (list2.Contains(list1[i]))
{
list1.Remove(i);
// list2.Remove(list2.IndexOf(list1[i]));
i--;
counter++;
}
Thanks all of you for your helps :)
Your answers are:
int[] sayilar1 = new int[150];
int[] sayilar2 = new int[150];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var rand = new Random();
for (int i = 0; i < sayilar1.Length; i++)
{
sayilar1[i] = rand.Next();
sayilar2[i] = rand.Next();
lvNumbers.Items.Add(sayilar1[i].ToString());
lvNumbers.Items.Add(sayilar2[i].ToString());
}
}
private void btnShuffle_Click(object sender, EventArgs e)
{
int[]newArray=BubbleSort();
for (int i = 0; i < newArray.Count(); i++)
{
lvSorted.Items.Add(newArray[i].ToString());
}
}
private int[] BubbleSort()
{
int temp = 0;
int[] newArray = new int[300];
for (int i = 0; i < 300; i++)
{
if (i < 150)
{
newArray[i] = sayilar1[i];
}
if (i >= 150)
newArray[i] = sayilar2[i - 150];
}
for (int i = 0; i < newArray.Length; i++)
{
for (int sort = 0; sort < newArray.Length - 1; sort++)
{
if (newArray[sort] > newArray[sort + 1])
{
temp = newArray[sort + 1];
newArray[sort + 1] = newArray[sort];
newArray[sort] = temp;
}
}
}
return newArray;
}
}
2.
private void btnTek_Click(object sender, EventArgs e)
{
lvFiltered.Items.Clear();
string[] sayilar = tbSayilar.Text.Split('\n');
int[] array = new int[sayilar.Length];
for (int i = 0; i < sayilar.Length; i++)
{
array[i] = int.Parse(sayilar[i]);
}
List<int> ayiklanmisSayilar = TekCiftAyir(array, "T");
for (int i = 0; i < ayiklanmisSayilar.Count; i++)
{
lvFiltered.Items.Add(ayiklanmisSayilar[i].ToString());
}
}
private void btnCift_Click(object sender, EventArgs e)
{
lvFiltered.Items.Clear();
string[] sayilar = tbSayilar.Text.Split('\n');
int[] array = new int[sayilar.Length];
for (int i = 0; i < sayilar.Length; i++)
{
array[i] = int.Parse(sayilar[i]);
}
List<int> ayiklanmisSayilar = TekCiftAyir(array, "C");
for (int i = 0; i < ayiklanmisSayilar.Count; i++)
{
lvFiltered.Items.Add(ayiklanmisSayilar[i].ToString());
}
}
private List<int> TekCiftAyir(int[] array, string TC)
{
List<int> ayiklanmisSayilar = new List<int>();
if (TC == "T")
{
for (int i = 0; i < array.Length; i++)
{
if (array[i] % 2 == 1)
{
ayiklanmisSayilar.Add(array[i]);
}
}
}
if (TC == "C")
{
for (int i = 0; i < array.Length; i++)
{
if (array[i] % 2 == 0)
{
ayiklanmisSayilar.Add(array[i]);
}
}
}
return ayiklanmisSayilar;
}
}