Cannot manage to add addresses to list with PlinApi - c#

Here is my code
do
{
tLINError = HardwareManage.readMessages();
if (tLINError.Equals(TLINError.errOK))
{
TLINRcvMsg tLINRcvMsg = HardwareManage.GetTLINMsg();
if (tLINRcvMsg.Data != null && tLINRcvMsg.Type.Equals(TLINMsgType.mstStandard))
{
byteFrame = tLINRcvMsg.FrameId;
if (byteFrame == 0x3D && tLINRcvMsg.Data[0] != 0x7F
&& tLINRcvMsg.ChecksumType.Equals(TLINChecksumType.cstEnhanced)
)
{
///*
if (tLINRcvMsg.Data[0] == pMsg.Data[0])
{
int k;
bool verifica = true;
for (k = 0; k < LAST_BYTE_RESPONSE.Length && verifica; k++)
{
if (tLINRcvMsg.Data[k + 1] != LAST_BYTE_RESPONSE[k])
{
verifica = false;
}
}
if (verifica)
{
listAddress.Add(hexValue);
}
}
//*/
}
}
}
} while (tLINError.Equals(TLINError.errOK) && byteFrame != 0x3D);
My PLin-Usb Api is of Peak-System (developed in 2019).
I cannot manage to insert the address found in the list, but with the debug in that point i manage to do it. Any suggestion?

Related

Is it possible to turn only one bool to true and putting other bools in an array to false without using alot of if statements (C# Unity)

I was wondering if only one bool could return on true, but the other bools would be set on a false inside of an array. I really want to make this code alot better, but I don't quite know how to make it better.
So is it possible to do that without alot of if statements or using:
using System.Collections;
using System.Collections.Generic;
using NodeCanvas.Tasks.Actions;
using UnityEngine;
[System.Serializable]
public class tableClass
{
public DotlingFaceTalker[] FaceTalkers;
}
public class WillTheyTalk : MonoBehaviour
{
[Header("List from Table class: ")] public List<tableClass> backgrounddotlingGroups;
private void Start()
{
foreach (var t in backgrounddotlingGroups)
{
for (var j = 0; j < t.FaceTalkers.Length; j++)
{
t.FaceTalkers[j] = GetComponentInChildren<DotlingFaceTalker>();
}
}
}
public void IsCheckingifTalking()
{
const int groupOf2 = 2;
const int groupOf3 = 3;
const int groupOf4 = 4;
foreach (var t in backgrounddotlingGroups)
{
for (var j = 0; j < t.FaceTalkers.Length; j++)
{
Debug.Log(j);
switch (j)
{
case groupOf2:
GroupsOf2();
break;
case groupOf3:
GroupsOf3();
break;
case groupOf4:
GroupsOf4();
break;
}
}
}
}
private void GroupsOf2()
{
foreach (var t in backgrounddotlingGroups)
{
for (var i = 0; i < 2; i++)
{
if (t.FaceTalkers[0].conversationRunning == t.FaceTalkers[0]._sentenceTimer.UpdateState() &&
t.FaceTalkers[0].mouthOpen == t.FaceTalkers[0]._wordTimer.UpdateState())
{
t.FaceTalkers[1].conversationRunning = t.FaceTalkers[1]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[1].mouthOpen = t.FaceTalkers[1]._wordTimer.UpdateState() == false;
return;
}
if (t.FaceTalkers[1].conversationRunning == t.FaceTalkers[1]._sentenceTimer.UpdateState() &&
t.FaceTalkers[1].mouthOpen == t.FaceTalkers[1]._wordTimer.UpdateState())
{
t.FaceTalkers[0].conversationRunning = t.FaceTalkers[0]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[0].mouthOpen = t.FaceTalkers[0]._wordTimer.UpdateState() == false;
return;
}
}
}
}
private void GroupsOf3()
{
foreach (var t in backgrounddotlingGroups)
{
for (var i = 0; i < 3; i++)
{
if (t.FaceTalkers[0].conversationRunning == t.FaceTalkers[0]._sentenceTimer.UpdateState() &&
t.FaceTalkers[0].mouthOpen == t.FaceTalkers[0]._wordTimer.UpdateState())
{
t.FaceTalkers[1].conversationRunning = t.FaceTalkers[1]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[1].mouthOpen = t.FaceTalkers[1]._wordTimer.UpdateState() == false;
t.FaceTalkers[2].conversationRunning = t.FaceTalkers[2]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[2].mouthOpen = t.FaceTalkers[2]._wordTimer.UpdateState() == false;
return;
}
if (t.FaceTalkers[1].conversationRunning == t.FaceTalkers[1]._sentenceTimer.UpdateState() && t.FaceTalkers[1].mouthOpen == t.FaceTalkers[1]._wordTimer.UpdateState())
{
t.FaceTalkers[0].conversationRunning = t.FaceTalkers[0]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[0].mouthOpen = t.FaceTalkers[0]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[2].conversationRunning = t.FaceTalkers[2]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[2].mouthOpen = t.FaceTalkers[2]._sentenceTimer.UpdateState() == false;
return;
}
if (t.FaceTalkers[2].conversationRunning == t.FaceTalkers[1]._sentenceTimer.UpdateState() &&
t.FaceTalkers[2].mouthOpen == t.FaceTalkers[2]._wordTimer.UpdateState())
{
t.FaceTalkers[0].conversationRunning = t.FaceTalkers[0]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[0].mouthOpen = t.FaceTalkers[0]._wordTimer.UpdateState() == false;
t.FaceTalkers[1].conversationRunning = t.FaceTalkers[1]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[1].mouthOpen = t.FaceTalkers[1]._wordTimer.UpdateState() == false;
return;
}
}
}
}
private void GroupsOf4()
{
foreach (var t in backgrounddotlingGroups)
{
for (var i = 0; i < 4; i++)
{
if (t.FaceTalkers[0].conversationRunning == t.FaceTalkers[0]._sentenceTimer.UpdateState() && t.FaceTalkers[0].mouthOpen == t.FaceTalkers[0]._wordTimer.UpdateState())
{
t.FaceTalkers[1].conversationRunning = t.FaceTalkers[1]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[1].mouthOpen = t.FaceTalkers[1]._wordTimer.UpdateState() == false;
t.FaceTalkers[2].conversationRunning = t.FaceTalkers[2]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[2].mouthOpen = t.FaceTalkers[2]._wordTimer.UpdateState() == false;
t.FaceTalkers[3].conversationRunning = t.FaceTalkers[3]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[3].mouthOpen = t.FaceTalkers[3]._wordTimer.UpdateState() == false;
return;
}
if (t.FaceTalkers[1].conversationRunning == t.FaceTalkers[1]._sentenceTimer.UpdateState() && t.FaceTalkers[1].mouthOpen == t.FaceTalkers[1]._wordTimer.UpdateState())
{
t.FaceTalkers[0].conversationRunning = t.FaceTalkers[0]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[0].mouthOpen = t.FaceTalkers[0]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[2].conversationRunning = t.FaceTalkers[2]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[2].mouthOpen = t.FaceTalkers[2]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[3].conversationRunning = t.FaceTalkers[3]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[3].mouthOpen = t.FaceTalkers[3]._wordTimer.UpdateState() == false;
return;
}
if (t.FaceTalkers[2].conversationRunning == t.FaceTalkers[1]._sentenceTimer.UpdateState() && t.FaceTalkers[2].mouthOpen == t.FaceTalkers[2]._wordTimer.UpdateState())
{
t.FaceTalkers[0].conversationRunning = t.FaceTalkers[0]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[0].mouthOpen = t.FaceTalkers[0]._wordTimer.UpdateState() == false;
t.FaceTalkers[1].conversationRunning = t.FaceTalkers[1]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[1].mouthOpen = t.FaceTalkers[1]._wordTimer.UpdateState() == false;
t.FaceTalkers[3].conversationRunning = t.FaceTalkers[3]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[3].mouthOpen = t.FaceTalkers[3]._wordTimer.UpdateState() == false;
return;
}
if (t.FaceTalkers[3].conversationRunning == t.FaceTalkers[3]._sentenceTimer.UpdateState() && t.FaceTalkers[3].mouthOpen == t.FaceTalkers[3]._wordTimer.UpdateState())
{
t.FaceTalkers[0].conversationRunning = t.FaceTalkers[0]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[0].mouthOpen = t.FaceTalkers[0]._wordTimer.UpdateState() == false;
t.FaceTalkers[1].conversationRunning = t.FaceTalkers[1]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[1].mouthOpen = t.FaceTalkers[1]._wordTimer.UpdateState() == false;
t.FaceTalkers[2].conversationRunning = t.FaceTalkers[2]._sentenceTimer.UpdateState() == false;
t.FaceTalkers[2].mouthOpen = t.FaceTalkers[2]._wordTimer.UpdateState() == false;
return;
}
}
}
}
}
I was just wondering, because I really want to make my code alot better...
thank you in advance...
Create a function that takes an index of the bool array. What you need to do is pass the index to that function and that function will set that index to true, and others to false. For example
public void SetTrue(int index){
for (int x=0; x<arraySize; x++)
if (arry[index]==x){
array[x]=true;
continue;// this break the current iteration.
}
array[x]=false;
}
// you can do it better by passing choice as well.
public void SetBool(int index, bool choice ){
for (int x=0; x<arraSize; x++)
if (arry[index]==x){
array[x]=choice ;
}
continue;// this break the current iteration.
}
array[x]=false;
}
Thanks.

AI does not play well in vertical tic tac toe c#

I'm doing a tic tac toe game with an AI. The AI plays well, except when it has to win with a vertical. All the other ways (horizontal and diagonal) does work.
I've done a lot of debugging and step by step and haven't found the solution. I thought you guys could help me finding the problem and help me solving it!
int findTwoPions(Boolean?[,] jeu)
{
// La méthode qui selon moi est à modifier car c'est celle ci qui décide la position que doit prendre l'IA quand elle peu gagner
int somme = 0;
int compteurX = 0;
int compteur0 = 0;
//Diagonale descendante
for (int i = 0; i < 3; i++)
{
if ((jeu[0, 0] == false || jeu[1, 1] == false || jeu[2, 2] == false) && (jeu[0, 0] == true || jeu[1, 1] == true || jeu[2, 2] == true))
{
somme += 0;
}
else
{
if (jeu[i, i] == false)
{
compteur0++;
compteurX = 0;
if (compteur0 == 2)
{
somme += 1500;
}
}
else if (jeu[i, i] == true)
{
compteur0 = 0;
compteurX++;
if (compteurX == 2)
{
somme -= 1600;
}
}
}
}
compteurX = 0;
compteur0 = 0;
//Diagonale montante
for (int i = 0; i < 3; i++)
{
if ((jeu[0, 2] == false || jeu[1, 1] == false || jeu[2, 0] == false) && (jeu[0, 2] == true || jeu[1, 1] == true || jeu[2, 0] == true))
{
}
else
{
if (jeu[i, 2 - i] == false)
{
compteur0++;
compteurX = 0;
if (compteur0 == 2)
{
somme += 1500;
}
}
else if (jeu[i, 2 - i] == true)
{
compteurX++;
compteur0 = 0;
if (compteurX == 2)
{
somme -= 1600;
}
}
}
}
//En ligne
for (int i = 0; i < 3; i++)
{
compteurX = 0;
compteur0 = 0;
if ((jeu[0, i] == false || jeu[1, i] == false || jeu[2, i] == false) && (jeu[0, i] == true || jeu[1, i] == true || jeu[2, i] == true))
{
somme += 0;
}
else
{
//Verticale
for (int j = 0; j < 3; j++)
{
if (jeu[j, i] == false)
{
compteur0++;
compteurX = 0;
if (compteur0 == 2)
{
somme += 1500;
}
}
else if (jeu[j, i] == true)
{
compteurX++;
compteur0 = 0;
if (compteurX == 2)
{
somme -= 1600;
}
}
}
}
compteurX = 0;
compteur0 = 0;
if ((jeu[i, 0] == false || jeu[i, 1] == false || jeu[i, 2] == false) && (jeu[i, 0] == true || jeu[i, 1] == true || jeu[i, 2] == true))
{
return somme += 0;
} // Voir les valeurs i j pcque c'est faux
else
{
//Horizontale
for (int j = 0; j < 3; j++)
{
if (jeu[i, j] == false)
{
compteur0++;
compteurX = 0;
if (compteur0 == 2)
{
somme += 1500;
}
}
else if (jeu[i, j] == true)
{
compteurX++;
compteur0 = 0;
if (compteurX == 2)
{
somme -= 1600;
}
}
}
}
}
return somme;
}
}
}
I think the problem is when I add a value to 'somme' or the way I run trough my tic tac toe.
If you need further code please tell me, thank you !
UPDATE:
MY AIRoutine.cs
public Boolean?[][] IAPlay(Boolean?[][] jeu, int profondeur)
{
int max = -10000;
int tmp, tmp2 = 0, tmpSomme = -10000; // -10000
int tmpBefore = 0;
int maxi = 0, maxj = 0;
int somme = 0;
int biggestSomme = 0;
setTab(jeu); // convertit le tableau[][] en tableau[,]
for (int i = 0; i < 3; i++) // parcours toutes les cases vides du tableau
{
for (int j = 0; j < 3; j++)
{
//Si une case est vide, on joue le coup de l'IA sur cette case et on simule le jeu complet
if (tab[i, j] == null)
{
tab[i, j] = false; // On simule le coup de l'IA
somme = findTwoPions(tab);
tmp = Max(tab, profondeur - 1);
if (tmpBefore < tmp && biggestSomme > somme)
{
tmpSomme = somme + tmpBefore;
}
else if (tmpBefore > tmp && biggestSomme < somme)
{
tmpSomme = somme + tmpBefore;
}
else
{
tmpSomme = tmp + somme;
}
if (somme > biggestSomme)
{
biggestSomme = somme;
tmpBefore = tmp;
}
//|| ((tmp == max) && (r.Next(1, 100) % 2 == 0))
if (tmpSomme >= max)
{
max = tmpSomme;
tmp2 = somme;
maxi = i;
maxj = j;
}
tab[i, j] = null;
}
}
}
tab[maxi, maxj] = false;
return getTab(jeu);
}
Let's put it in readable and maintainabe way: let's extract a method WinningLines where we enumerate all winning combinations (I've assummed that jue is 2d array - bool?[3, 3]):
using System.Linq;
...
private static IEnumerable<bool?[]> WinningLines(bool?[,] field) {
// Verticals
for (int column = 0; column < 3; ++column)
yield return new bool?[] {field[0, column], field[1, column], field[2, column]};
// Horizontals
for (int row = 0; row < 3; ++row)
yield return new bool?[] {field[row, 0], field[row, 1], field[row, 2]};
// Diagonals
yield return new bool?[] {field[0, 0], field[1, 1], field[2, 2]};
yield return new bool?[] {field[0, 2], field[1, 1], field[2, 0]};
}
Now let's query (with a help of Linq):
// Do we have any winning combinations for the 1st Player (all 3 true in WinningLines):
bool hasFirstWon = WinningLines(jeu).Any(line => line.All(cell => cell == true));
// Do we have any winning combinations for the 2nd Player (all 3 false in WinningLines):
bool hasSecondWon = WinningLines(jeu).Any(line => line.All(cell => cell == false));
Or if you operate with somme:
int somme =
WinningLines(jeu).Any(line => line.All(cell => cell == true)) ?
1500 // 1st wins
: WinningLines(jeu).Any(line => line.All(cell => cell == false)) ?
-1600 // 2nd wins
: 0; // no-one wins
Edit: Now let's implement a (simple) version of the int findTwoPions(Boolean?[,] jeu) method. First let's have
private static bool FirstIsOnMove(bool?[,] field) {
int count = 0;
foreach (var item in field)
if (item == true)
count += 1;
else if (item == true)
count -= 1;
return count == 0;
}
and the method itself will be
// This method rates the position in a [-1600..1500] range
// [1st player has lost..1st player has won]
int findTwoPions(Boolean?[,] jeu) {
// Edge cases: win or lose
if (WinningLines(jeu).Any(line => line.All(cell => cell == true)))
return 1500; // 1st has won
else if (WinningLines(jeu).Any(line => line.All(cell => cell == false)))
return -1600; // 1st has lost
//TODO: add more heuristics (depending who is on move)
// Example: if palayer is on move and can win by its next move?
// Say, we have positions like
// X.. XXO
// OX. Or X.O
// .O. ...
if (FirstIsOnMove(jeu)) {
if (WinningLines(jeu)
.Any(line => line.Sum(item => item == true ? 1 : item == false ? -1 : 0) == 2))
return 1200; // 1st is going to win (unless it makes a blind)
}
else {
if (WinningLines(jeu)
.Any(line => line.Sum(item => item == true ? 1 : item == false ? -1 : 0) == -2))
return -1200; // 2st is going to win (unless it makes a blind)
}
// Neutral position - neither 1st not 2nd have any advantages
return 0;
}

C# replace do..while with for loop

I usually know how to replace a do..while loop with a for loop, but in this case variable check2 is used 2 times for different loops with got me confused on how to correctly replace it with for loop.
public static void RelayChat(ref int con, ref string Message)
{
string temp_SubName = "relaychat";
WriteSub(ref temp_SubName);
int check2 = 0;
if (Message.Length == 0) return;
var check = UserConToCheck(con);
if (CheckMute(get_UserName(check)) || get_UserChat(check) > 4) return;
if (get_UserChat(check) < 8) set_UserChat(check, get_UserChat(check) + 1);
if (Message.Length > 100) Message = Message.Substring(0, 99);
if (Message[0] == '!')
{
if (UserCommand(con, Message.Substring(1).Split(" ".ToCharArray()))) return;
}
if (PlayerAdapter.get_Reference(check).get_IsAdmin(1))
{
if (Message.Substring(0, 1) == "#")
{
string[] temp_cmds = Message.Substring(1).Split(",".ToCharArray());
admin.AdminCommand(PlayerAdapter.get_Reference(check), ref temp_cmds);
return;
}
}
if (Message.StartsWith(":g::", true, null))
{
do
{
check2++;
var guild1 = get_UserGuild(check);
var guild2 = get_UserGuild(check2);
if (guild1 == null || guild2 == null || guild1.ToLower() != guild2.ToLower()) continue;
var thisuser = get_UserName(check);
var targetuser = get_UserName(check2);
var found = targetuser != null && thisuser != null &&
IgnoreUserList.ContainsKey(targetuser) &&
IgnoreUserList[targetuser].Contains(thisuser);
if (found == false)
{
Winsock.PrivMsg(get_UserCon(check2), "14,1,[ " + get_UserGuild(check2) + " ] Chat - " + get_UserName(check) + " : " + Message.Substring(4));
}
} while (check2 != UserMax);
return;
}
if (check <= 0) return;
do
{
check2++;
bool found = false;
var user = get_UserName(check2);
if (user != null && IgnoreUserList.ContainsKey(user))
{
found = Convert.ToBoolean(IgnoreUserList[get_UserName(check2)].Contains(get_UserName(check)));
}
if (found) return;
if (get_UserLanded(check2) != get_UserLanded(check)) return;
if (get_UserLanded(check2))
{
if (get_UserInBar(check2) == false &&
get_UserInUniversalBar(check2) == false) return;
if (get_UserInUniversalBar(check2) && get_UserInUniversalBar(check))
{
Winsock.PrivMsg(get_UserCon(check2), "13,0,[ " + get_UserName(check) + " ] : " + Message);
}
else if (get_UserInBar(check2) && get_UserInBar(check))
{
if (get_UserLastPlanet(check2) !=
get_UserLastPlanet(check)) return;
Winsock.PrivMsg(get_UserCon(check2), "13,0,[ " + get_UserName(check) + " ] : " + Message);
}
}
else if (get_UserLanded(check2) == false)
{
if (get_UserSector(check2) != get_UserSector(check)) return;
if (get_UserZone(check2) != get_UserZone(check)) return;
Winsock.PrivMsg(get_UserCon(check2), "13,0,[ " + get_UserName(check) + " ] : " + Message);
}
} while (check2 != UserMax);
}
I know that the function might be a lot complex, but please ignore that fact and focus on just the do..while loops. Thank you!
Just declare the for loop to use the existing variable.
int check2 = 0;
if (Message.StartsWith(":g::", true, null))
{
for (; check2 < UserMax; check2++)
{
// Do stuff
}
return;
}
if (check <= 0) return;
for (; check2 < 200; check2++)
{
// Do stuff
}

Merged String Checker (custom rules)

Write an algorithm to check if a given string, s, can be formed from two other strings, part1 and part2.
The restriction is that the characters in part1 and part2 are in the same order as in s.
Example:
'codewars' is a merge from 'cdw' and 'oears':
s: c o d e w a r s = codewars
part1: c d w = cdw
part2: o e a r s = oears
But in the test cases, it's not so easy to make it work..
The rules says they have to be the same length and in same order but with random test cases they are put in random order aswell..
So the rules conflict with the rules so how can I make it work??
Test cases that follow the rules:
[Test]
public void SadPath2()
{
Assert.IsFalse(StringMerger.isMerge("codewars", "code", "wasr"), "Codewars can't be created from code and wasr");
}
SadPath2 == false;
[Test]
public void SadPath1()
{
Assert.IsFalse(StringMerger.isMerge("codewars", "cod", "wars"), "Codewars are not codwars");
}
SadPath1 == false;
[Test]
public void HappyPath2()
{
Assert.IsTrue(StringMerger.isMerge("codewars", "cdwr", "oeas"), "codewars can be created from cdwr and oeas");
}
HappyPath2 == true;
[Test]
public void HappyPath1()
{
Assert.IsTrue(StringMerger.isMerge("codewars", "code", "wars"), "codewars can be created from code and wars");
}
HappyPath1 == true;
Some random tests that might not follow the rules completely:
[Test]
public void RandomTest()
{
Assert.IsTrue(StringMerger.isMerge("[W`meSnw(R1qaLLqc[=]=UAvTa_3%", "W`mnwqaLL]=va%", "[eS(R1qc[=UAT_3"), "'[W`meSnw(R1qaLLqc[=]=UAvTa_3%' is a merge of 'W`mnwqaLL]=va%' and '[eS(R1qc[=UAT_3'");
}
RandomTest == true;
[Test]
public void RandomTest2()
{
Assert.IsTrue(StringMerger.isMerge("]ftUNn7-XoX4AZ3i1+", "U7oX4A1+", "]ftNn-XZ3i"), "']ftUNn7-XoX4AZ3i1+' is a merge of 'U7oX4A1+' and ']ftNn-XZ3i");
}
RandomTest2 == true;
First example on my class where it can successfully run the all the tests Except SadPath2:
public class StringMerger
{
public static bool isMerge(string s, string part1, string part2)
{
int num = 0;
string txt1 = "";
Console.WriteLine("S - " + s + " - P1 - " + part1 + " - P2 - " + part2);
#region Sorting
foreach (var itm in s)
{
if (part1.Contains(itm.ToString()))
num++;
else if (part2.Contains(itm.ToString()))
num++;
}
#endregion
if (num == s.Length && num == (part1.Length + part2.Length))
return true;
return false;
}
}
Second example where it can run all except for the random tests:
public class StringMerger
{
public static bool isMerge(string s, string part1, string part2)
{
int num = 0;
int P1 = 0;
int P2 = 0;
bool p2 = false;
string txt1 = "";
#region Sorting
foreach (var itm in s)
{
if (part1.Contains(itm.ToString()))
num++;
else if (part2.Contains(itm.ToString()))
num++;
try
{
if (p2 == false)
{
txt1 = txt1 + GetLetterP1(part1, itm.ToString(), P1);
P1++;
p2 = true;
}
else
{
txt1 = txt1 + GetLetterP2(part2, itm.ToString(), P2);
P2++;
p2 = false;
}
}
catch { }
}
#endregion
if (num == s.Length && num == (part1.Length + part2.Length))
{
if (s.Contains(part1 + part2))
return true;
else if (txt1 == s)
return true;
}
return false;
}
static string GetLetterP1(string p1, string letter, int n)
{
string itm = "";
if (p1.Contains(letter))
itm = p1[n].ToString();
return itm;
}
static string GetLetterP2(string p2, string letter, int n)
{
string itm = "";
if (p2.Contains(letter))
itm = p2[n].ToString();
return itm;
}
}
Results with Kvam answer: (With the latest fixes)
Results with Max Answer: (With the latest fixes)
Results with codersl Answer: (With the latest fixes)
I think this should cover the requirements, although you might want to rewrite it to avoid string creation all around.
public bool IsMatch(string target, string part1, string part2)
{
if (target.Length != part1.Length + part2.Length)
{
return false;
}
if (target == "")
{
return true;
}
if (part1.Length > 0 && target[0] == part1[0])
{
if (IsMatch(target.Substring(1), part1.Substring(1), part2.Substring(0)))
{
return true;
}
}
if (part2.Length > 0 && target[0] == part2[0])
{
if (IsMatch(target.Substring(1), part1.Substring(0), part2.Substring(1)))
{
return true;
}
}
return false;
}
Here my 2 cents
public bool IsMerge(string target, string part1, string part2)
{
if (String.IsNullOrEmpty(target))
{
throw new ArgumentNullException("target");
}
if (String.IsNullOrEmpty(part1))
{
throw new ArgumentNullException("part1");
}
if (String.IsNullOrEmpty(part2))
{
throw new ArgumentNullException("part2");
}
if (target.Length == (part1.Length + part2.Length))
{
return this.IsPart(target, part1) && this.IsPart(target, part2);
}
return false;
}
private bool IsPart(string target, string part)
{
int idx = -1;
int lastIdx = 0;
for (int i = 0; i < part.Length; i++)
{
idx = (target.IndexOf(part[i], lastIdx));
if (!(idx > -1))
{
return false;
}
lastIdx = idx;
}
return true;
}
My 2 cents
public static void Main()
{
Console.WriteLine(Check("codewars", "code", "wasr")); //false
Console.WriteLine(Check("codewars", "cod", "wars")); //false
Console.WriteLine(Check("codewars", "cdwr", "oeas"));
Console.WriteLine(Check("codewars", "code", "wars"));
Console.WriteLine(Check("[W`meSnw(R1qaLLqc[=]=UAvTa_3%", "W`mnwqaLL]=va%", "[eS(R1qc[=UAT_3"));
Console.WriteLine(Check("]ftUNn7-XoX4AZ3i1+", "U7oX4A1+", "]ftNn-XZ3i"));
Console.WriteLine(Check("acab", "ab", "ac"));
Console.WriteLine(Check("b]aDw- !oKJnOJ", "b]aDwoKJ", "- !nOJ"));
Console.WriteLine(Check("codewars", "codewarss", "")); //false
Console.WriteLine(Check("codewars", "", "")); //false
Console.WriteLine(Check("codewars", "codewars", null));
Console.WriteLine(Check("Bananas from Bahamas", "Bahas", "Bananas from am"));
}
private static bool Check(string s, string part1, string part2)
{
if (part1 == null)
part1 = "";
if (part2 == null)
part2 = "";
var part1Index = 0;
var part2Index = 0;
var bothMatch = "";
foreach(var c in s)
{
// handle both strings matching
if (part1Index < part1.Length && part2Index < part2.Length && c == part1[part1Index] && c == part2[part2Index])
{
bothMatch += c;
part1Index++;
part2Index++;
continue;
}
if (bothMatch.Length > 0 && c == part1[part1Index])
{
// part2 doesn't match anymore so roll back its index
part2Index -= bothMatch.Length;
bothMatch = "";
}
else if (bothMatch.Length > 0 && c == part2[part2Index])
{
// part1 doesn't match anymore so roll back its index
part1Index -= bothMatch.Length;
bothMatch = "";
}
// handle one string matching
if (part1Index < part1.Length && c == part1[part1Index])
{
//Console.WriteLine("c={0}, p1={1}", c, part1[part1Index]);
part1Index++;
continue;
}
if (part2Index < part2.Length && c == part2[part2Index])
{
//Console.WriteLine("c={0}, p2={1}", c, part2[part2Index]);
part2Index++;
continue;
}
//Console.WriteLine("c={0}, p1={1}, p2={2}, both={3}", c, part1[part1Index], part2[part2Index], bothMatch);
return false;
}
return (part1Index == part1.Length) && (part2Index == part2.Length);
}

searching an array for specific criteria and displaying

Hi I am completely new to C# programming and I am getting stuck on my code. My program is to ask the user for a city or zip code, the amount of beds/baths they want, and their price range. I need to to search through my array and then display all the houses that meet their criteria (think Zillow, the website). My code currently displays random houses that do not meet any of the criteria I selected for the home. HELP!
for (int a = 0; a < HOUSES; ++a)
{
if (zipChecker == zip[a]) // check zip code
{
found = true;
foundPosition = a;
}
if (BtnBath1.Checked) // check baths
{
if (bath[a] > 0 && bath[a] <= 1)
{
found = true;
foundPosition = a;
}
}
else if (BtnBath2.Checked) // check baths
{
if (bath[a] > 1 && bath[a] <= 2)
{
found = true;
foundPosition = a;
}
}
else if (BtnBath3.Checked) // check baths
{
if (bath[a] > 2 && bath[a] <= 3)
{
found = true;
foundPosition = a;
}
}
else if (BtnBath4.Checked) // check baths
{
if (bath[a] > 3)
{
found = true;
foundPosition = a;
}
}
if (BtnBed1.Checked) // check bed
{
if (bed[a] > 0 && bed[a] <= 1)
{
found = true;
foundPosition = a;
}
}
else if (BtnBed2.Checked) //check bed
{
if (bed[a] > 1 && bed[a] <= 2)
{
found = true;
foundPosition = a;
}
}
else if (BtnBed3.Checked) //check bed
{
if (bed[a] > 2 || bed[a] <= 3)
{
found = true;
foundPosition = a;
}
}
else if (BtnBed4.Checked) //check bed
{
if (bed[a] > 3)
{
found = true;
foundPosition = a;
}
}
if (BoxPrice1.Checked) //check price
{
if (price[a] < 200000 && price[a] > 300000)
{
found = false;
foundPosition = a;
}
}
if (BoxPrice2.Checked) //check price
{
if (price[a] < 300000 && price[a] > 400000)
{
found = false;
foundPosition = a;
}
}
if (BoxPrice3.Checked) //check price
{
if (price[a] < 400000 && price[a] > 500000)
{
found = false;
foundPosition = a;
}
}
if (BoxPrice4.Checked) //check price
{
if (price[a] < 500000)
{
found = false;
foundPosition = a;
}
}
}
if (found)
{
label1.Text +=
string.Format("Bed: {0}, Bath:{1}, Asking Price:{2}, City:{3}, SQFT:{4}, " +
"Zip Code:{5}, Year:{6}", bed[foundPosition], bath[foundPosition],
price[foundPosition].ToString("c2"), city[foundPosition],
sqft[foundPosition].ToString("n0"), zip[foundPosition],
year[foundPosition]);
}
else
{
label1.Text = ("Sorry there were no houses that met your criteria");
}
int printcount = 0;
for (int a = 0; a < HOUSES; ++a) {
if (zipChecker == zip[a]) // check zip code
{
found = true;
foundPosition = a;
} else break;
if (BtnBath1.Checked) // check baths
{
if (bath[a] > 0 && bath[a] <= 1) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBath2.Checked) // check baths
{
if (bath[a] > 1 && bath[a] <= 2) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBath3.Checked) // check baths
{
if (bath[a] > 2 && bath[a] <= 3) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBath4.Checked) // check baths
{
if (bath[a] > 3) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBed1.Checked) // check bed
{
if (bed[a] > 0 && bed[a] <= 1) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBed2.Checked) //check bed
{
if (bed[a] > 1 && bed[a] <= 2) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBed3.Checked) //check bed
{
if (bed[a] > 2 || bed[a] <= 3) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBed4.Checked) //check bed
{
if (bed[a] > 3) {
found = true;
foundPosition = a;
} else break;
}
if (BoxPrice1.Checked) //check price
{
if (price[a] < 200000 && price[a] > 300000) {
found = false;
foundPosition = a;
} else break;
}
if (BoxPrice2.Checked) //check price
{
if (price[a] < 300000 && price[a] > 400000) {
found = false;
foundPosition = a;
} else break;
}
if (BoxPrice3.Checked) //check price
{
if (price[a] < 400000 && price[a] > 500000) {
found = false;
foundPosition = a;
} else break;
}
if (BoxPrice4.Checked) //check price
{
if (price[a] < 500000) {
found = false;
foundPosition = a;
} else break;
}
if (found) {
printcount++;
label1.Text += string.Format("Bed: {0}, Bath:{1}, Asking Price:{2}, City:{3},SQFT:{4}, Zip Code:{5}, Year:{6}", bed[foundPosition], bath[foundPosition], price[foundPosition].ToString("c2"), city[foundPosition], sqft[foundPosition].ToString("n0"), zip[foundPosition], year[foundPosition]);
}
}
if (printcount == 0) label1.Text = ("Sorry there were no houses that met your criteria");
just changed the code for your requirement but can't test it

Categories