I've got a booking service in which you can select by an enum if you want to display all seats, all available seats or all booked seats.
My problem is that I don't know how to make it so i.e. only the booked seats are shown, because as of now if I select "only booked seats" it shows the correct number of reserved seats, but it iterates from the beginning of the entire array instead of the ones that I want, so if there are 3 reserved seats, it will show seat 0,1,2 instead of the ones that are actually reserved.
I am pretty sure that I need to change the for (int i = 0; i < count; i++) to for (int i = 0; i < totalNumberOfSeats; i++) instead to actually loop through all seats instead of just as many as there are of the kind that I want to display, but then I get out of bound exception and I don't know how to proceed.
public string[] GetSeatInfoStrings(DisplayOptions choice)
{
int count = GetNumOfSeats(choice);
if (count <= 0)
{
return null;
}
string[] strSeatInfoStrings = new string[count];
for (int i = 0; i < count; i++)
{
strSeatInfoStrings[i] = GetSeatInfoAt(i);
}
return strSeatInfoStrings;
}
public string GetSeatInfoAt(int index)
{
int row = GetRow(index);
int col = GetCol(index);
string seatInfo;
if (string.IsNullOrEmpty(GetName(m_nameMatrix[row, col])))
{
seatInfo = MarkAsVacant(row, col);
}
else
{
seatInfo = MarkAsReserved(row, col);
}
return seatInfo;
}
I've got a method IsReserved(int index) and tried something like this
if (IsReserved(i))
{
// Want to return all seats that are reserved
}
else if (!IsReserved(i))
{
// Want to return all seats that are NOT reserved
}
As far as for that method working, it is okay, but the problem is that I don't know what to put within the brackets.
This is a question where we cant help without knowing your complete model. There is little detail. May be you want something like this:
string[] strSeatInfoStrings = new string[count];
int counter = 0;
for (int i = 0; i < totalNumberOfSeats; i++)
{
var seatInfo = GetSeatInfoAt(i);
if (seatInfo == "reserved") //some kind of checking
{
strSeatInfoStrings[counter] = seatInfo;
counter++; //run another counter
}
}
return strSeatInfoStrings;
You can avoid all the hassle of array and counter and just use a List<T>..
var strSeatInfoStrings = new List<string>();
for (int i = 0; i < totalNumberOfSeats; i++)
{
var seatInfo = GetSeatInfoAt(i);
if (seatInfo == "reserved") //some kind of checking
strSeatInfoStrings.Add(seatInfo);
}
return strSeatInfoStrings;
It's probably easier to use a List than an array in this case, because with a List you don't need to know the size before you start adding to it.
public string[] GetSeatInfoStrings(DisplayOptions choice)
{
List<string> lstSeatInfoStrings = new List<string>();
for (int i = 0; i < totalNumberOfSeats; i++)
{
string seatInfo = GetSeatInfoAt(i);
if (seatInfo.Reserved)
{
lstSeatInfoStrings.Add(seatInfo);
}
}
if (lstSeatInfoStrings.Count == 0)
{
return null;
}
return lstSeatInfoStrings.ToArray();
}
Related
I am wondering if strings have functionality that can see if a string contains words or words and other types of characters in general. (ideally I want to only consider strings that have readable sentences but that may too advanced) I am trying to count strings in a list that have that kind of text. I do not want to add to the count any strings that are only numbers, blank spaces, tabs or symbols (like ?, #, #) or even random letters unless there is at least some words contained in the string.
The strings will be initialised with "" so the code in the if statement - (this.ElementAt(i).getNotarised().ElementAt(j).getError() != "") - would be fine if there was no input at all. Unfortunately I am expecting some input in some case so this case also counts scenarios where there are only spaces, number, symbols or all of the 3 - which I do not want.
this is referring to a class inheriting from List
.getNotarised() returns a List
/** Find the highest/lowest amount of errors/solutions/suggestions/comments.
* If it's ASC then return the lowest to highest.
* If it's DESC then return the highest to lowest.
* Return a list with LOGS in the correct order.
* */
public List<LOG> highORlow(string asc_desc, string category)
{
int count = 0;
int[] array = new int[this.Count()];
for(int i = 0; i <= this.Count()-1; i++)
{
for(int j = 0; j <= this.ElementAt(i).getNotarised().Count()-1; j++)
{
if(this.ElementAt(i).getNotarised().ElementAt(j).getError() != "")
{
++count;
}
}
array[i] = count;
}
return new List<LOG>();
}
Point of interest:
string pattern = "[A-Za-z]{5}[0-9]{0}";
Regex xp = new Regex(pattern);
Use xp.IsMatch() to check if the pattern is matched.
/** Find the highest/lowest amount of errors/solutions/suggestions/comments.
* If it's true (ASC) then return the lowest to highest.
* If it's false (DESC) then return the highest to lowest.
* Return a list with LOGS in the correct order.
* */
public List<LOG> highORlow(bool asc_desc, string category)
{
int count = 0;
string pattern = "[A-Za-z]{5}[0-9]{0}";
Regex xp = new Regex(pattern);
Dictionary<LOG, int> array = new Dictionary<LOG, int>();
for (int i = 0; i <= this.Count() - 1; i++)
{
for (int j = 0; j <= this.ElementAt(i).getNotarised().Count() - 1; j++)
{
if (category == "ERROR")
{
if (xp.IsMatch(this.ElementAt(i).getNotarised().ElementAt(j).getError()))
{
++count;
continue;
}
}
if (category == "SOLUTION")
{
if (xp.IsMatch(this.ElementAt(i).getNotarised().ElementAt(j).getSolution()))
{
++count;
continue;
}
}
if (category == "SUGGESTION")
{
if (xp.IsMatch(this.ElementAt(i).getNotarised().ElementAt(j).getSuggestion()))
{
++count;
continue;
}
}
if (category == "COMMENT")
{
if (xp.IsMatch(this.ElementAt(i).getNotarised().ElementAt(j).getComment()))
{
++count;
continue;
}
}
}
array.Add(this.ElementAt(i), count);
count = 0;
}
List<LOG> list = new List<LOG>();
if(asc_desc)
{
foreach (KeyValuePair<LOG, int> v in array.OrderBy(key => key.Value))
{
list.Add(v.Key);
}
}
else
{
foreach (KeyValuePair<LOG, int> v in array.OrderByDescending(key => key.Value))
{
list.Add(v.Key);
}
}
return list;
}```
I was doing a coding test (for practice) that went something like this:
Input is a string with |'s and *'s.
E.g. **|*|*|**|***
Implement the function:
List<int> countItems(string line, List<int> startLocations, List<int> endLocations)
Count the number of * characters that are between an opening and closing pair of | characters.
Where the 2 locations are arrays with the start and end locations (indices) to consider withing the string line.
For example if line = *|*|* and startLocations = [1] and endLocations = [3] it means
I need to check the substring *|*.
And since there is only 1 pipe, the result is zero.
The location values seemed to be 1-based and not 0-based for some reason.
If the range was 1 and 5, for example, the result would be 1 because there is only 1 * between pipes.
The code I came up with that did manage to solve about half the test cases is as follows:
List<int> countItems(string line, List<int> startLocations, List<int> endLocations)
{
var results = new List<int>();
if (String.IsNullOrWhiteSpace(line) || startLocations.Count == 0)
{
return results;
}
for (var i = 0; i < startLocations.Count; i++)
{
var startIndex = startLocations[i] - 1;
var endIndex = endLocations[i] - 1;
var start = false;
var total = 0;
var tempTotal = 0;
for (var j = startIndex; j < endIndex; j++)
{
if (!start && line[j] == '|')
{
start = true;
tempTotal = 0;
}
else if (start && line[j] == '*')
{
tempTotal++;
}
else if (line[j] == '|')
{
total += tempTotal;
tempTotal = 0;
}
}
if (line[endIndex] == '|')
{
total += tempTotal;
}
results.Add(total);
}
return results;
}
All the test cases either passed or failed because it ran out of time.
The error said it exceeded a time of 3 seconds.
Now I couldn't see the actual data being passed into the tests, so I'm not able to test it more.
But I suspect the solution was some kind of temporary list or dictionary so as to only iterate over the string 1 time instead of many times as in my code.
I want to learn what kind of solution to use in cases like this, but not really sure if this is a common type of question where the solution has some kind of name or common concept.
I would appreciate any obvious pointers to solving this type of question or even links to similar programming challenges where I can practice more.
In this case I think the best option would be to use stack theory.
It is a variation of the parenthesis balancing problem. You can find more about it here
Article parenthesis balancing problem
I managed to redo the test and I found the answer and problem type.
This is a "plates between candles" type of problem.
I was trying to solve it myself but almost ran out of time and eventually just copy/pasted an answer I found.
This was a practice run, not an actual test or application.
This was the solution that worked... I'll be studying it to better understand it...
List<int> numberOfItems(string s, List<int> startIndices, List<int> endIndices)
{
int q = startIndices.Count;
int l = s.Length;
for (var i = 0; i < startIndices.Count; i++)
{
startIndices[i]--;
endIndices[i]--;
}
var ans = new List<int>();
var prev = new int[l];
var next = new int[l];
var preSum = new int[l];
int p = -1, nxt = -1;
// calculating prev candle up to this index.
for (int i = 0; i < l; i++)
{
if (s[i] == '|')
{
p = i;
}
prev[i] = p;
}
//Calculating next candle from this index.
for (int i = l - 1; i >= 0; i--)
{
if (s[i] == '|')
{
nxt = i;
}
next[i] = nxt;
}
int c = 0;
// calculating the number of stars between these indices.
for (int i = 0; i < l; i++)
{
if (s[i] == '*')
{
c++;
}
preSum[i] = c;
}
// calculating ans.
for (int k = 0; k < q; k++)
{
int i = startIndices[k];
int j = endIndices[k];
int right = prev[j];// position of left candle.
int left = next[i];// position of right candle.
//cout<<right<<left;
if (left == -1 || right == -1 || left > right)
{
ans.Add(0);
}
else
{
ans.Add(preSum[right] - preSum[left]);
}
}
return ans;
}
I am a complete beginner in programming. Trying to make sorting a choice. Everything seems to be ok. Only there is one caveat. Only numbers up to 24 index are filled in the new array. I can’t understand what the problem is.
int[] Fillin(int[] mass)
{
Random r = new Random();
for(int i = 0; i < mass.Length; i++)
{
mass[i] = r.Next(1, 101);
}
return mass;
}
int SearchSmall(int[] mass)
{
int smallest = mass[0];
int small_index = 0;
for(int i = 1; i < mass.Length; i++)
{
if (mass[i] < smallest)
{
smallest = mass[i];
small_index = i;
}
}
return small_index;
}
int[] Remove(int[] massiv,int remind)
{
List<int> tmp = new List<int>(massiv);
tmp.RemoveAt(remind);
massiv = tmp.ToArray();
return massiv;
}
public int[] SortMass(int[] mass)
{
mass = Fillin(mass);
Print(mass);
Console.WriteLine("________________________________");
int[] newmass = new int[mass.Length];
int small;
for(int i = 0; i < mass.Length; i++)
{
small = SearchSmall(mass);
newmass[i] = mass[small];
mass = Remove(mass, small);
}
return newmass;
}
I think your main issue is that when you remove an element in the Remove function, the main loop in for (int i = 0; i < mass.Length; i++) will not check all elements o the initial array. A simple (and ugly) way to fix that would be not to remove the elements but to assign a very high value
public static int[] Remove(int[] massiv, int remind)
{
massiv[remind] = 999999;
return massiv;
}
Or as Legacy suggested simply modify the mass.length for newmass.lengh in the main loop.
As some others have mentioned this is not the best way to order an array, but it is an interesting exercise.
String list G is :
[0] : {"1,2,5"}
[1] : {"1,2,4,5,6"}
[2] : {"2,4,6"}
[3] : {"1,4,6"}
With the following commands, we conclude that "1,4" exists in the List G[3] :
if (G[i].Contains("1,4")) { //code here }
How to modify the above commands, that in addition feature (Contains), "1,4" exists in the List G[1]?
Program codes
for (int i = 0; i < candid.Count; i++)
{
foreach (TransactionTP b in transactions)
{
string search = candid[i];
var searchNumbers = search.Split(',').Select(int.Parse).ToList();
for (int j = 0; j < G.Count; j++)
{
IEnumerable<int> numbers = G[j].Split(',').Select(int.Parse);
int idx = 0;
foreach (var number in numbers)
{
if (number == searchNumbers[idx])
{
idx++;
}
if (idx == searchNumbers.Count)
{
arraye[i] = arraye[i] + (b.transactionUtility);
break;
}
}
}
}
}
Update:
The order of the searched term matters.
In order to preserve the ordering of the set you are matching go (4,1 in this case), you will need to evaluate each string, keeping track of where you are in the match.
string[] G = new[]
{
"1,2,5",
"1,2,4,5,6",
"2,4,6",
"1,4,6"
};
string search = "1,4";
var searchNumbers = search.Split(',').Select(int.Parse).ToList();
for (int i = 0; i < G.Length; i++)
{
// Convert the string into an enumeration of numbers
IEnumerable<int> numbers = G[i].Split(',').Select(int.Parse);
// Index to keep track of the search
int idx = 0;
// Loop through the input set sequentially
foreach (var number in numbers)
{
// Check if the input matches the next expected number
if (number == searchNumbers[idx])
{
idx++;
}
if (idx == searchNumbers.Count)
{
Console.WriteLine("String {0} matched", G[i]);
break;
}
}
}
Replace your single Contains call with a method that does this:
bool passes = false;
for(int i = 0; i < G.Length; i++)
{
List<string> temp = new List<string>();
if(G[i].Contains(","))
{
temp = G[i].Split(",");
}
else
{
temp = G[i];
}
if(temp.Contains("1") && temp.Contains("4")
{
passes = true;
}
}
return passes;
This eliminates the possibility of matching on "10" or "41" etc etc
It also will not care if your elements are sorted, even though you said they are. It will also match regardless of the number of entries between "1" and "4" in the list.
You could spice this up to take any number of inputs that you want to match before qualifying as a match, I'll leave that to you if you want to make it so.
I am trying to get positions in a list of some values to compare them with another list.
for (int i = 0; i <= commands.ToArray().Length; i++)
{
levensheteinvalues_commands.Add(commands.ToArray()[i].ToString());
levensheteinvalues_numbers.Add(
Program.ComputeLevenshteinDistance(args[0],
commands.ToArray()[i].ToString()));
}
for (int i = 0; i <= commands.ToArray().Length; i++)
{
if (smallestlevensheteinvalue == 0)
{
smallestlevensheteinvalue = levensheteinvalues_numbers[i];
}
else if (smallestlevensheteinvalue > levensheteinvalues_numbers[i])
{
smallestlevensheteinvalue = levensheteinvalues_numbers[i];
}
}
var indexes = levensheteinvalues_numbers.GetIndexes(smallestlevensheteinvalue);
Why doesn't
var indexes = levensheteinvalues_numbers.GetIndexes(smallestlevensheteinvalue);
work? And when I get the value how can I compare it to another list?
The code you have posted have some serious problems. This May solve your problem since your code as well as your approach is very unclear and ambiguous. I have blindly edited the code to fix the serious problems.
for (int i = 0; i < commands.Count(); i++) {
levensheteinvalues_commands.Add(commands.ElementAt(i).ToString());
Program.ComputeLevenshteinDistance(args[0], commands.ElementAt(i).ToString()));
}
for (int i = 0; i < commands.Count(); i++) {
if (smallestlevensheteinvalue == 0)
{
smallestlevensheteinvalue = levensheteinvalues_numbers[i];
}
else if (smallestlevensheteinvalue > levensheteinvalues_numbers[i])
{
smallestlevensheteinvalue = levensheteinvalues_numbers[i];
}
}
int index = levensheteinvalues_numbers.IndexOf(levensheteinvalues_numbers.Min());