Given a list of numbers, determine whether it can represent the pre-order traversal list of a binary search tree (BST) - preorder

Given a list of numbers, determine whether it can represent the pre-order traversal list of a binary search tree (BST).
public boolean isValid(int[] arr)
{
int root = arr[0];
int i=1;
while( i< arr.length && root >arr[i])
{
i++;
}
for(;i<arr.length;i++)
{
if(arr[i] <root)
{
return false;
}
}
return true;
}
The above function works for most of the cases ex {3,4,5,1,2}, {3, 2, 1, 5, 4, 6}, {1,2,3}.
But it doesn't work for {1,3,4,2}.
Can anybody help me to fix the issue.

The Idea is take a list of more that 3 elements you can identify left, right and root in a BST like the first three elements. Now it is a pre-order if and only if left<=root<=right. Now root go in to the stack and take the next 3 and apply the same logic.
Make this till you have less than three element:
Two elements become left and root with the rule left<=root
One element is just a root
In both cases you must put root in stack.
Now take the stack and apply the same logic ... till you have just one element in the stack that means it is a pre-order BST.
Now write it as recursive function is pretty trivial and funny.

Related

Clingo flexible but maximum count of literals and how to prevent negation cycles

I'm programming a Sudoku solver and have come across two problems.
I would like to generate a specific number of literals, but keep the total number flexible
How can I prevent a negation cycle, so that I have a clean solution for declaring a digit as not possible?
General code with generator regarding my first question:
row(1..3). %coordinates are declared via position of sub-grid (row, col) and position of
col(1..3). %field in sub-grid (sr, sc)
sr(1..3).
sc(1..3).
num(1..9).
1 { candidate(R,C,A,B,N) : num(N) } 9 :- row(R), col(C), sr(A), sc(B).
Here I want to create all candidates for a field, which at the beginning are all the numbers from 1 to 9. So I want for all candidate(1,1,1,1,1-9). But it would be nice to keep the number of candidates for each field flexible, so I can declare a solution if through integrity constraints like
:- candidate(R,C,A,B,N), solution(R1,C,A1,B,N), R != R1, A != A1. %excludes candidates if digit is present in solution in same column
I have excluded all 8 other candidates:
solution(R,C,A,B,N) :- candidate(R,C,A,B,N), { N' : candidate(R,C,A,B,N') } = 1.
Regarding my second question, I basically want to declare a solution, if a specific condition is fulfilled. The problem is, if I have a solution, the condition is no longer true and this leads to a negation cycle:
solution(R,C,A,B,N) :- candidate(R,C,A,B,N), { set1(R',C',A',B') } = { posDigit(N') }, { negDigit(N'') } = { set2(R'',C'',A'',B'') } - 1, not taken(R,C,A,B), not takenDigit(N).
taken(R,C,A,B) :- solution(R,C,A,B,N).
I would be glad I somebody offers input on how to solve these problems.

Array Performing XOR On Itself With Offset

Trying to implement an autocorrelation algorithm, meaning, for example:
let exampleData: [Float] = [1, 2, 3, 4, 5]
Trying to find the fastest way to evaluate 1 ^ 2 + 2 ^ 3 + 3 ^ 4 + 4 ^ 5.
Essentially, iterate through the array, and for every element, calculate the result of XOR between it and another element a set distance away.
Trouble is, this also has to be done for many different values of the offset.
Right now I just have a nested for loop, and I don't know how to make it faster...
var data: [Bool]
var result: [Int]
...
for offset in start..<end {
for index in 0..<(end - offset) {
if (data[index] ^ data[index + frequency]) {
result[offset] += 1
}
}
}
Sounds like you might want windows(ofCount:) from swift-algorithms:
https://github.com/apple/swift-algorithms/blob/main/Guides/Windows.md
That will give you a sliding window through any collection, and if your offset is relatively small (or you actually want the whole window, e.g. to do a moving average), that will be great.
The swift-algorithms stuff is nice since it's more optimized than whatever you'll do ad hoc, plus offers lazy eval.
You might also consider aligning and zipping up your sequence and then mapping over that, e.g.:
zip(data, data.dropFirst(offset))
.map { $0 ^ $1 }
...and so on

Why Iam getting ReferenceOutOfRangeException while PlayerPref a list in Unity [duplicate]

I have some code and when it executes, it throws a IndexOutOfRangeException, saying,
Index was outside the bounds of the array.
What does this mean, and what can I do about it?
Depending on classes used it can also be ArgumentOutOfRangeException
An exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll but was not handled in user code Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
What Is It?
This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than or equal to the number of elements it contains.
When It Is Thrown
Given an array declared as:
byte[] array = new byte[4];
You can access this array from 0 to 3, values outside this range will cause IndexOutOfRangeException to be thrown. Remember this when you create and access an array.
Array Length
In C#, usually, arrays are 0-based. It means that first element has index 0 and last element has index Length - 1 (where Length is total number of items in the array) so this code doesn't work:
array[array.Length] = 0;
Moreover please note that if you have a multidimensional array then you can't use Array.Length for both dimension, you have to use Array.GetLength():
int[,] data = new int[10, 5];
for (int i=0; i < data.GetLength(0); ++i) {
for (int j=0; j < data.GetLength(1); ++j) {
data[i, j] = 1;
}
}
Upper Bound Is Not Inclusive
In the following example we create a raw bidimensional array of Color. Each item represents a pixel, indices are from (0, 0) to (imageWidth - 1, imageHeight - 1).
Color[,] pixels = new Color[imageWidth, imageHeight];
for (int x = 0; x <= imageWidth; ++x) {
for (int y = 0; y <= imageHeight; ++y) {
pixels[x, y] = backgroundColor;
}
}
This code will then fail because array is 0-based and last (bottom-right) pixel in the image is pixels[imageWidth - 1, imageHeight - 1]:
pixels[imageWidth, imageHeight] = Color.Black;
In another scenario you may get ArgumentOutOfRangeException for this code (for example if you're using GetPixel method on a Bitmap class).
Arrays Do Not Grow
An array is fast. Very fast in linear search compared to every other collection. It is because items are contiguous in memory so memory address can be calculated (and increment is just an addition). No need to follow a node list, simple math! You pay this with a limitation: they can't grow, if you need more elements you need to reallocate that array (this may take a relatively long time if old items must be copied to a new block). You resize them with Array.Resize<T>(), this example adds a new entry to an existing array:
Array.Resize(ref array, array.Length + 1);
Don't forget that valid indices are from 0 to Length - 1. If you simply try to assign an item at Length you'll get IndexOutOfRangeException (this behavior may confuse you if you think they may increase with a syntax similar to Insert method of other collections).
Special Arrays With Custom Lower Bound
First item in arrays has always index 0. This is not always true because you can create an array with a custom lower bound:
var array = Array.CreateInstance(typeof(byte), new int[] { 4 }, new int[] { 1 });
In that example, array indices are valid from 1 to 4. Of course, upper bound cannot be changed.
Wrong Arguments
If you access an array using unvalidated arguments (from user input or from function user) you may get this error:
private static string[] RomanNumbers =
new string[] { "I", "II", "III", "IV", "V" };
public static string Romanize(int number)
{
return RomanNumbers[number];
}
Unexpected Results
This exception may be thrown for another reason too: by convention, many search functions will return -1 (nullables has been introduced with .NET 2.0 and anyway it's also a well-known convention in use from many years) if they didn't find anything. Let's imagine you have an array of objects comparable with a string. You may think to write this code:
// Items comparable with a string
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
myArray[Array.IndexOf(myArray, "Debug")]);
// Arbitrary objects
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
myArray[Array.FindIndex(myArray, x => x.Type == "Debug")]);
This will fail if no items in myArray will satisfy search condition because Array.IndexOf() will return -1 and then array access will throw.
Next example is a naive example to calculate occurrences of a given set of numbers (knowing maximum number and returning an array where item at index 0 represents number 0, items at index 1 represents number 1 and so on):
static int[] CountOccurences(int maximum, IEnumerable<int> numbers) {
int[] result = new int[maximum + 1]; // Includes 0
foreach (int number in numbers)
++result[number];
return result;
}
Of course, it's a pretty terrible implementation but what I want to show is that it'll fail for negative numbers and numbers above maximum.
How it applies to List<T>?
Same cases as array - range of valid indexes - 0 (List's indexes always start with 0) to list.Count - accessing elements outside of this range will cause the exception.
Note that List<T> throws ArgumentOutOfRangeException for the same cases where arrays use IndexOutOfRangeException.
Unlike arrays, List<T> starts empty - so trying to access items of just created list lead to this exception.
var list = new List<int>();
Common case is to populate list with indexing (similar to Dictionary<int, T>) will cause exception:
list[0] = 42; // exception
list.Add(42); // correct
IDataReader and Columns
Imagine you're trying to read data from a database with this code:
using (var connection = CreateConnection()) {
using (var command = connection.CreateCommand()) {
command.CommandText = "SELECT MyColumn1, MyColumn2 FROM MyTable";
using (var reader = command.ExecuteReader()) {
while (reader.Read()) {
ProcessData(reader.GetString(2)); // Throws!
}
}
}
}
GetString() will throw IndexOutOfRangeException because you're dataset has only two columns but you're trying to get a value from 3rd one (indices are always 0-based).
Please note that this behavior is shared with most IDataReader implementations (SqlDataReader, OleDbDataReader and so on).
You can get the same exception also if you use the IDataReader overload of the indexer operator that takes a column name and pass an invalid column name.
Suppose for example that you have retrieved a column named Column1 but then you try to retrieve the value of that field with
var data = dr["Colum1"]; // Missing the n in Column1.
This happens because the indexer operator is implemented trying to retrieve the index of a Colum1 field that doesn't exist. The GetOrdinal method will throw this exception when its internal helper code returns a -1 as the index of "Colum1".
Others
There is another (documented) case when this exception is thrown: if, in DataView, data column name being supplied to the DataViewSort property is not valid.
How to Avoid
In this example, let me assume, for simplicity, that arrays are always monodimensional and 0-based. If you want to be strict (or you're developing a library), you may need to replace 0 with GetLowerBound(0) and .Length with GetUpperBound(0) (of course if you have parameters of type System.Array, it doesn't apply for T[]). Please note that in this case, upper bound is inclusive then this code:
for (int i=0; i < array.Length; ++i) { }
Should be rewritten like this:
for (int i=array.GetLowerBound(0); i <= array.GetUpperBound(0); ++i) { }
Please note that this is not allowed (it'll throw InvalidCastException), that's why if your parameters are T[] you're safe about custom lower bound arrays:
void foo<T>(T[] array) { }
void test() {
// This will throw InvalidCastException, cannot convert Int32[] to Int32[*]
foo((int)Array.CreateInstance(typeof(int), new int[] { 1 }, new int[] { 1 }));
}
Validate Parameters
If index comes from a parameter you should always validate them (throwing appropriate ArgumentException or ArgumentOutOfRangeException). In the next example, wrong parameters may cause IndexOutOfRangeException, users of this function may expect this because they're passing an array but it's not always so obvious. I'd suggest to always validate parameters for public functions:
static void SetRange<T>(T[] array, int from, int length, Func<i, T> function)
{
if (from < 0 || from>= array.Length)
throw new ArgumentOutOfRangeException("from");
if (length < 0)
throw new ArgumentOutOfRangeException("length");
if (from + length > array.Length)
throw new ArgumentException("...");
for (int i=from; i < from + length; ++i)
array[i] = function(i);
}
If function is private you may simply replace if logic with Debug.Assert():
Debug.Assert(from >= 0 && from < array.Length);
Check Object State
Array index may not come directly from a parameter. It may be part of object state. In general is always a good practice to validate object state (by itself and with function parameters, if needed). You can use Debug.Assert(), throw a proper exception (more descriptive about the problem) or handle that like in this example:
class Table {
public int SelectedIndex { get; set; }
public Row[] Rows { get; set; }
public Row SelectedRow {
get {
if (Rows == null)
throw new InvalidOperationException("...");
// No or wrong selection, here we just return null for
// this case (it may be the reason we use this property
// instead of direct access)
if (SelectedIndex < 0 || SelectedIndex >= Rows.Length)
return null;
return Rows[SelectedIndex];
}
}
Validate Return Values
In one of previous examples we directly used Array.IndexOf() return value. If we know it may fail then it's better to handle that case:
int index = myArray[Array.IndexOf(myArray, "Debug");
if (index != -1) { } else { }
How to Debug
In my opinion, most of the questions, here on SO, about this error can be simply avoided. The time you spend to write a proper question (with a small working example and a small explanation) could easily much more than the time you'll need to debug your code. First of all, read this Eric Lippert's blog post about debugging of small programs, I won't repeat his words here but it's absolutely a must read.
You have source code, you have exception message with a stack trace. Go there, pick right line number and you'll see:
array[index] = newValue;
You found your error, check how index increases. Is it right? Check how array is allocated, is coherent with how index increases? Is it right according to your specifications? If you answer yes to all these questions, then you'll find good help here on StackOverflow but please first check for that by yourself. You'll save your own time!
A good start point is to always use assertions and to validate inputs. You may even want to use code contracts. When something went wrong and you can't figure out what happens with a quick look at your code then you have to resort to an old friend: debugger. Just run your application in debug inside Visual Studio (or your favorite IDE), you'll see exactly which line throws this exception, which array is involved and which index you're trying to use. Really, 99% of the times you'll solve it by yourself in a few minutes.
If this happens in production then you'd better to add assertions in incriminated code, probably we won't see in your code what you can't see by yourself (but you can always bet).
The VB.NET side of the story
Everything that we have said in the C# answer is valid for VB.NET with the obvious syntax differences but there is an important point to consider when you deal with VB.NET arrays.
In VB.NET, arrays are declared setting the maximum valid index value for the array. It is not the count of the elements that we want to store in the array.
' declares an array with space for 5 integer
' 4 is the maximum valid index starting from 0 to 4
Dim myArray(4) as Integer
So this loop will fill the array with 5 integers without causing any IndexOutOfRangeException
For i As Integer = 0 To 4
myArray(i) = i
Next
The VB.NET rule
This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than equal to the number of elements it contains. the maximum allowed index defined in the array declaration
Simple explanation about what a Index out of bound exception is:
Just think one train is there its compartments are D1,D2,D3.
One passenger came to enter the train and he have the ticket for D4.
now what will happen. the passenger want to enter a compartment that does not exist so obviously problem will arise.
Same scenario: whenever we try to access an array list, etc. we can only access the existing indexes in the array. array[0] and array[1] are existing. If we try to access array[3], it's not there actually, so an index out of bound exception will arise.
To easily understand the problem, imagine we wrote this code:
static void Main(string[] args)
{
string[] test = new string[3];
test[0]= "hello1";
test[1]= "hello2";
test[2]= "hello3";
for (int i = 0; i <= 3; i++)
{
Console.WriteLine(test[i].ToString());
}
}
Result will be:
hello1
hello2
hello3
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
Size of array is 3 (indices 0, 1 and 2), but the for-loop loops 4 times (0, 1, 2 and 3). So when it tries to access outside the bounds with (3) it throws the exception.
A side from the very long complete accepted answer there is an important point to make about IndexOutOfRangeException compared with many other exception types, and that is:
Often there is complex program state that maybe difficult to have control over at a particular point in code e.g a DB connection goes down so data for an input cannot be retrieved etc... This kind of issue often results in an Exception of some kind that has to bubble up to a higher level because where it occurs has no way of dealing with it at that point.
IndexOutOfRangeException is generally different in that it in most cases it is pretty trivial to check for at the point where the exception is being raised. Generally this kind of exception get thrown by some code that could very easily deal with the issue at the place it is occurring - just by checking the actual length of the array. You don't want to 'fix' this by handling this exception higher up - but instead by ensuring its not thrown in the first instance - which in most cases is easy to do by checking the array length.
Another way of putting this is that other exceptions can arise due to genuine lack of control over input or program state BUT IndexOutOfRangeException more often than not is simply just pilot (programmer) error.
These two exceptions are common in various programming languages and as others said it's when you access an element with an index greater than the size of the array. For example:
var array = [1,2,3];
/* var lastElement = array[3] this will throw an exception, because indices
start from zero, length of the array is 3, but its last index is 2. */
The main reason behind this is compilers usually don't check this stuff, hence they will only express themselves at runtime.
Similar to this:
Why don't modern compilers catch attempts to make out-of-bounds access to arrays?

Better way to find sums in a grid in Swift

I have an app with a 6x7 grid that lets the user input values. After each value is obtained the app checks to find if any of the consecutive values create a sum of ten and executes further code (which I have working well for the 4 test cases I've written). So far I've been writing if statements similar to the below:
func findTens() {
if (rowOneColumnOnePlaceHolderValue + rowOneColumnTwoPlaceHolderValue) == 10 {
//code to execute
} else if (rowOneColumnOnePlaceHolderValue + rowOneColumnTwoPlaceHolderValue + rowOneColumnThreePlaceHolderValue) == 10 {
//code to execute
} else if (rowOneColumnOnePlaceHolderValue + rowOneColumnTwoPlaceHolderValue + rowOneColumnThreePlaceHolderValue + rowOneColumnFourPlaceHolderValue) == 10 {
//code to execute
} else if (rowOneColumnOnePlaceHolderValue + rowOneColumnTwoPlaceHolderValue + rowOneColumnThreePlaceHolderValue + rowOneColumnFourPlaceHolderValue + rowOneColumnFivePlaceHolderValue) == 10 {
//code to execute
}
That's not quite halfway through row one, and it will end up being a very large set of if statements (231 if I'm calculating correctly, since a single 7 column row would be 1,2-1,2,3-...-2,3-2,3,4-...-67 so 21 possibilities per row). I think there must be a more concise way of doing it but I've struggled to find something better.
I've thought about using an array of each of the rowXColumnYPlaceHolderValue variables similar to the below:
let rowOnePlaceHolderArray = [rowOneColumnOnePlaceHolderValue, rowOneColumnTwoPlaceHolderValue, rowOneColumnThreePlaceHolderValue, rowOneColumnFourPlaceHolderValue, rowOneColumnFivePlaceHolderValue, rowOneColumnSixPlaceHolderValue, rowOneColumnSevenPlaceHolderValue]
for row in rowOnePlaceHolderArray {
//compare each element of the array here, 126 comparisons
}
But I'm struggling to find a next step to that approach, in addition to the fact that those array elements then apparently because copies and not references to the original array anymore...
I've been lucky enough to find some fairly clever solutions to some of the other issues I've come across for the app, but this one has given me trouble for about a week now so I wanted to ask for help to see what ideas I might be missing. It's possible that there will not be another approach that is significantly better than the 231 if statement approach, which will be ok. Thank you in advance!
Here's an idea (off the top of my head; I have not bothered to optimize). I'll assume that your goal is:
Given an array of Int, find the first consecutive elements that sum to a given Int total.
Your use of "10" as a target total is just a special case of that.
So I'll look for consecutive elements that sum to a given total, and if I find them, I'll return their range within the original array. If I don't find any, I'll return nil.
Here we go:
extension Array where Element == Int {
func rangeOfSum(_ sum: Int) -> Range<Int>? {
newstart:
for start in 0..<count-1 {
let slice = dropFirst(start)
for n in 2...slice.count {
let total = slice.prefix(n).reduce(0,+)
if total == sum {
return start..<(start+n)
}
if total > sum {
continue newstart
}
if n == slice.count && total < sum {
return nil
}
}
}
return nil
}
}
Examples:
[1, 8, 6, 2, 8, 4].rangeOfSum(10) // 3..<5, i.e. 2,8
[1, 8, 1, 2, 8, 4].rangeOfSum(10) // 0..<3, i.e. 1,8,1
[1, 8, 3, 2, 9, 4].rangeOfSum(10) // nil
Okay, so now that we've got that, extracting each possible row or column from the grid (or whatever the purpose of the game is) is left as an exercise for the reader. 🙂

Union of disjoint sets

I am looking at disjoint sets that support the function of the Union.
The technique of height reduction of a tree:
We always merge the smaller tree to the greater one, i.e. we make the root of the smaller tree to point to the root of the greater tree.
A tree is greater than an other if it has more nodes.
Each node is a struct with fields: some information for the element, the pointer "parent" to the parent node, and a counter "count", that is used only if the node is the root and contains the number of the nodes at the up-tree.
The following algorithm merges two up trees:
pointer UpTreeUnion(pointer S,T) {
if (S == NULL OR P == NULL) return;
if (S->count >= T->count) {
S->count = S->count + T->count;
T->parent = S;
return S;
}
else {
T->count = T->count + S->count;
S->parent = T;
return T;
}
}
Consider an implementation of disjoint sets with union, where there can be at most k disjoint sets.
The implementation uses a hash table A[0.. max-1] at which there are stored keys based on the method ordered double hashing.
Let h1 and h2 be the primary and the secondary hash function, respectively. A contains the keys of the nodes of all of the above trees and also a pointer to the corresponding node for each of them.
I want to write an algorithm that takes as parameters the keys of two nodes and merges the up-trees to which the nodes belong (the nodes can belong to any up-trees, even at the same in which case it appears an appropriate message). At merging, we should apply techniques of path compression and height reduction.
Could you give me a hint how we could do this?
Suppose that we have this array:
At the beginning the nodes will be like that:
Then if k1=100, k2=5, after applying the algorithm, will we get this?
Then if we have k1=59, k2=5, we will get the following:
Right? Then applying the path compression we start doing this:
tmp=B
while (B->parent!=B)
parent=B->parent;
tmp->parent=B;
tmp=parent;
}
So we will have parent=F, tmp->parent=B, tmp=F.
How do we continue?
Having then k1=14, k2=59 we get this:
First, when you get keys, you need to find them in the hash table.
Hash table contains entries: (key, pointer-to-node).
Let's say you want to find key k. You check:
A[h1(k) + 0*h2(k) mod size(A)] - if it contains key k, you read corresponding pointer-to-node.
If there is something other than k, you check:
A[h1(k) + 1*h2(k) mod size(A)],
A[h1(k) + 2*h2(k) mod size(A)],
A[h1(k) + i*h2(k) mod size(A)]... until you find key k.
Now that you have pointers to 2 nodes, you need to find roots of the trees those nodes belong to. To find the root, you go up the tree until you reach root node. You use parent pointer of each node for it and you can assume that root's parent pointer points to itself for example.
Now that you have 2 roots, you can merge them using upTreeUnion.
Path compression works like this:
After you have found root of a tree for node s, you follow the path from s to root one more time and set parent pointer of every node on the path to the root.
Update:
Algorithm(k1,k2){
int i=0,j=0;
int i1,i2;
while (i<max and A[i1 = h1(k1)+i*h2(k1) mod size(A)]->key!=k1){
i++;
}
while (j<max and A[i2 = h1(k2)+j*h2(k2) mod size(A)]->key!=k2){
j++;
}
if (A[i1]->key!=k1) return;
if (A[i2]->key!=k2) return;
pointer node1,node2,root1,root2;
node1=A[i1]->node;
node2=A[i2]->node;
root1=UpTreeFind(node1);
root2=UpTreeFind(node2);
if (root1==root2){
printf("The nodes belong to the same up tree");
return;
}
// path compression
pointer tmp,tmpParent;
tmp = node1;
while (tmp->parent!=root1) {
tmpParent=tmp->parent;
tmp->parent=root1;
tmp=tmpParent;
}
tmp = node2;
while (tmp->parent!=root2) {
tmpParent=tmp->parent;
tmp->parent=root2;
tmp=tmpParent;
}
UpTreeUnion(root1,root2);
}