Problem: Two of the nodes of a Binary Search Tree (BST) are swapped. Fix (or correct) the BST without changing its structure.
I've googled a lot and found that most of the solutions assume that the BST doesn't have any duplicate values, which makes it quite trivial to find the swapped elements. However my question is how to find the swapped elements if there are duplicate values in the BST. I can't find any solutions dealing with this case and hope someone could give an algorithm to solve this.
Thanks.
Given: A BST with any two nodes swapped
If the given tree is still a binary search tree, it is not possible for you to know which nodes were swapped (since, we don't have any other information about the previous state of the tree)
Key-Point: After Swap if the BST properties are being violated at any two points, then we can identify the 2 swapped nodes.
We can modify the algorithm to find if a given binary tree a bst (using min-max approach) to solve this problem:
DriverFunction (TreeNode *root)
{
TreeNode *swapped1 = NULL
TreeNode *swapped2 = NULL
FindSwapped ( root,
swapped1,
swapped2,
INT_MIN,
INT_MAX)
if (swapped1 && swapped2)
Print Swapped Nodes
// If you also want to correct the BST,
// Swap the data of nodes pointed out by swapped1 & swapped2
}
void FindSwapped (TreeNode *root,
TreeNode *swapped1,
TreeNode *swapped2,
int minval,
int maxval)
1. if (NULL == root)
2. return
3. if (root->data <= minval || root->data > maxval)
4. if (NULL != swapped1)
5. swapped2 = root
6. return
7. else
8. swapped1 = root
9. FindSwapped (root->LC,
swapped1,
swapped2,
minval,
root->data)
10.FindSwapped (root->RC,
swapped1,
swapped2,
root->data,
maxval)
It should work well for your problem. Please let me know in case of any concerns, I will modify the algorithm if something is missed out.
Related
I want to delete an element of a linked list, and for that i have to compare the elements with the one given in the header, but the value is a structure and I cant compare 2 structures. So I guess I need to get a pointer to that structure and compare those two. How is that done? Thats kinda the function:
void delete_element(NodList* head, Structure value){
NodList* moving;
while (moving->next != NULL && moving->val != value){
left_behind = moving;
moving = moving->next;
}
//in the rest i delete if its matching and move the pointers
I am trying to see if I can use ZoKrates in a scenario where a user can prove to the verifier that age is over 21 years without revealing the date of birth. I think its a good use case for zero-knowledge proof but like to understand the best way to implement it.
The circuit code (sample) takes the name of the user as public input(name attestation is done by a trusted authority like DMV and is a most likely combination of offline/online mechanism), then the date of birth which is a private input.
//8297122105 = "Razi" is decimal.
def main(pubName,private yearOfBirth, private centuryOfBirth):
x = 0
y = 0
z = 0
x = if centuryOfBirth == 19 then 1 else 0 fi
y = if yearOfBirth < 98 then 1 else 0 fi
z = if pubName == 8297122105 then 1 else 0 fi
total = x + y + z
result = if total == 3 then 1 else 0 fi
return result
Now, using ./target/release/zokrates generate-proof command get the output that can be used as an input toverifier.sol.
A = Pairing.G1Point(0x24cdd31f8e07e854e859aa92c6e7f761bab31b4a871054a82dc01c143bc424d, 0x1eaed5314007d283486826e9e6b369b0f1218d7930cced0dd0e735d3702877ac);
A_p = Pairing.G1Point(0x1d5c046b83c204766f7d7343c76aa882309e6663b0563e43b622d0509ac8e96e, 0x180834d1ec2cd88613384076e953cfd88448920eb9a965ba9ca2a5ec90713dbc);
B = Pairing.G2Point([0x1b51d6b5c411ec0306580277720a9c02aafc9197edbceea5de1079283f6b09dc, 0x294757db1d0614aae0e857df2af60a252aa7b2c6f50b1d0a651c28c4da4a618e], [0x218241f97a8ff1f6f90698ad0a4d11d68956a19410e7d64d4ff8362aa6506bd4, 0x2ddd84d44c16d893800ab5cc05a8d636b84cf9d59499023c6002316851ea5bae]);
B_p = Pairing.G1Point(0x7647a9bf2b6b2fe40f6f0c0670cdb82dc0f42ab6b94fd8a89cf71f6220ce34a, 0x15c5e69bafe69b4a4b50be9adb2d72d23d1aa747d81f4f7835479f79e25dc31c);
C = Pairing.G1Point(0x2dc212a0e81658a83137a1c73ac56d94cb003d05fd63ae8fc4c63c4a369f411c, 0x26dca803604ccc9e24a1af3f9525575e4cc7fbbc3af1697acfc82b534f695a58);
C_p = Pairing.G1Point(0x7eb9c5a93b528559c9b98b1a91724462d07ca5fadbef4a48a36b56affa6489e, 0x1c4e24d15c3e2152284a2042e06cbbff91d3abc71ad82a38b8f3324e7e31f00);
H = Pairing.G1Point(0x1dbeb10800f01c2ad849b3eeb4ee3a69113bc8988130827f1f5c7cf5316960c5, 0xc935d173d13a253478b0a5d7b5e232abc787a4a66a72439cd80c2041c7d18e8);
K = Pairing.G1Point(0x28a0c6fff79ce221fccd5b9a5be9af7d82398efa779692297de974513d2b6ed1, 0x15b807eedf551b366a5a63aad5ab6f2ec47b2e26c4210fe67687f26dbcc7434d);
Question
Consider a scenario when a user (say Razi) can take the proof above (probably in a form of a QR code) and scan it on a machine (confirms age is over 21) that will run the verifierTx method on the contract. Since the proof explicitly has "Razi" inside the proof and contract can verify the age without knowing the actual date of birth we get a better privacy. However, the challenge is now anyone else can reuse the proof since it was used within the transaction. One way to mitigate this issue is to make sure that either the proof is valid for a limited time or (just may good for one-time use). Another way is to ensure proof of user's identity ("Razi"), in a way that is satisfied beyond doubt (e.g. by confirming identity on blockchain etc.).
Are there ways to make sure proof can be used by a user more than once?
I hope the question and explanation make sense. Happy to elaborate more on this, so let me know.
What you will need is:
Razi owning an ethereum public/private key
a (salted) fingerprint fact (e.g. birthday as unix timestamp) associated with Razi's public ethereum address and endorsed on-chain by an authority
Now you can write a ZoKrates program like this
def main(private field salt, private field birthdayAsUnixTs, field pubFactHashA, field pubFactHashB, field ts) -> (field)
// check that the fact is corresponding to the endorsed salted fact fingerprint onchain
h0, h1 = sha256packed(0,0,salt,birthdayAsUnixTs)
h0 == pubFactHashA
h1 == pubFactHashB
// 18 years is pseudo code only!
field ok = if birthdayAsUnixTs * 18 years <= ts then 1 else 0 fi
return ok
Now in your contract you can
check that msg.sender is the owner of the endorsed fact
require(ts <= now)
call verifier with the proof and public input: (factHash, ts, 1)
You can do that by hashing the proof and adding that hash in a list of "used proofs", so no one can use it again.
Now, ZoKrates add randomness in the generation of the proof in order to prevent revealing that the same witnesss has been used, since zkproofs do not show anything about the witness. So, if you want to prevent the person to use his credential (accredit that he is over 21 years old ) more than once you have to use a nullifier (See ZCash approach in the "How zk-SNARKs are applied to create a shielded transaction" part).
Basically you use a string with the data of Razi nullifier_string = centuryOfBirth+yearOfBirth+pubName and then you publish it Hash nullifier = H(nullifier_string) in a table of revealed nullifiers. In the ZoKrates scheme you have to add the nullifier as a public input and then verify that the nullifier corresponds to the data provided. Something like this:
import "utils/pack/unpack128.code" as unpack
import "hashes/sha256/256bitPadded.code" as hash
import "utils/pack/nonStrictUnpack256.code" as unpack256
def main(pubName,private yearOfBirth, private centuryOfBirth, [2]field nullifier):
field x = if centuryOfBirth == 19 then 1 else 0 fi
field y = if yearOfBirth < 98 then 1 else 0 fi
field z = if pubName == 8297122105 then 1 else 0 fi
total = x + y + z
result = if total == 3 then 1 else 0 fi
null0 = unpack(nullifier[0])
null1 = unpack(nullifier[1])
nullbits = [...null0,...null1]
nullString = centuryOfBirth+yearOfBirth+pubName
unpackNullString = unpack256(nullString)
nullbits == hash(unpackNullString)
return result
This has to be made in order to prevent that Razi provide a random nullifier unrelated to his data.
Once you had done this, you can check if the nullifier provided has been already used if it is registered in the revealed nullifier table.
The problem with this in your case is that the year of birth is a weak number to hash. Someone can do a brute-force attack to the nullifier and reveal the year of birth of Razi. You have to add a strong number in the verification (Razi secret ID? a digital signature?) to prevent this attack.
Note1: I have an old version of ZoKrates, so check the import path right.
Note2: Check the ZoKrates Hash function implementation, you may have problem with the padding of the inputs, the unpack256 function prevent this I suppose, but you can double check this to prevent bugs.
I know the method to find the middle element in singly linked list by going through it only once.
Is there some way to find the Mean of the elements in a list?
Based on your comments I suppose you are asking about arithmetic mean (http://en.wikipedia.org/wiki/Mean#Arithmetic_mean_.28AM.29 )
Also if you know how many elements are there you can get rid of count.
Node current = root;
double sum = 0;
int count = 0;
while (current != null) {
sum += current.el;
count++;
current = current.next;
}
System.out.println(sum/count);
I need help, maybe I am blind. Here is a fragment of my code:
System.out.println("itemPropertyIDS="+item.getItemPropertyIds().toString());
System.out.println("argname="+argName);
Property<?> p = item.getItemProperty(argName);
if (p != null) {
System.out.println("p="+p.toString());
return p.getValue();
}
// Continue ...
It returns a currious null value instead of continue, even if the propertyId doesn't exists.
This is written on my console:
itemPropertyIDS=[iconName, iconResource, nodeType, nodeValue, nodeName, handler, nodeData]
argname=Lab
p=com.vaadin.data.util.IndexedContainer$IndexedContainerProperty#12967
The first row shows list of property names.
I expected getTtemProperty must return null, but not.
The item comes from IndexedContainer.
Can you help me? Any idea? Thanky You.
I tested your code and indeed - property p is not null even though property doesn't exist in IndexedContainer. Reading the comments of Vaadin ticket pasted by kris54321, it makes sense not fixing the bug as some applications may rely on that feature. Fixing the bug may break those apps.
Possible workarounds for this problem:
Check directly the propertyId-collection if property exists in the container:
if(item.getItemPropertyIds().contains(argName) {
Property<?> p = item.getItemProperty(argName);
System.out.println("p="+p.toString());
return p.getValue()
}
Change the logic to check property value
if(item.getItemProperty(argname).getValue() != null) }
//Do things
{
I was forced to make workaround using "item.getItemPropertyIds().contains(argName)". For me, the priority is to check whether the item contains the value (null possible) or not. If yes then I use the value (can be null) else another activity is done.
If they dont want to fix the bug due to application using the bug, then the documentation should be fixed, else all novices in Vaadin (as I am) will be confused.
The implementation in IndexedContainer$IndexedContainer is wrong:
#Override
public Property getItemProperty(Object id) {
return new IndexedContainerProperty(itemId, id);
}
This can never return null as the documentation says.
So I have a Peptide, which is a string of letters, corresponding to aminoacids
Say the peptide is
peptide_sequence = "VEILANDQGNR"
And it has a modification on L at position 4 and R at position 11,
I would like to insert a "<span class=\"modified_aa\"> and </span> before and after those positions at the same time.
Here is what I tried:
My modifications are stored in an array pep_mods of objects modification containing an attribute location with the position, in this case 4 and 11
pep_mods.each do |m|
peptide_sequence.gsub(peptide_sequence[m.position.to_i-1], "<span class=\"mod\">#{#peptide_sequence[m.location.to_i-1]}</span>" )
end
But since there are two modifications after the first insert of the html span tag the positions in the string become all different
How could I achieve what I intend to do? I hope it was clear
You should work backwards- make the modification starting with the last one. That way the index of earlier modifications is unchanged.
You might need to sort the array of indices in reverse order - then you can use the code you currently have.
Floris's answer is correct, but if you want to do it the hard way (O(n^2) instead of O(nlgn)) here is the basic idea.
Instead of relying on gsub you can iterate over the characters checking if each has an index corresponding to one of the modifications. If the index matches, perform the modification. Otherwise, keep the original character.
modified = peptide_sequence.each_with_index
.to_a
.map do |c, i|
pep_mods.each do |m|
if m.location.to_i = i
%Q{<span class="mod">#{c}</span>}
else
c
end
end
end.join('')
Ok, just in case this is helpful for anyone else, this is how I finally did it:
I first converted the peptide sequence to an array :
pep_seq_arr = peptide_sequence.split("")
then used each_with_index as Casey mentioned
pep_seq_arr.each_with_index do |aa, i|
pep_mods.each do |m|
pep_seq_arr[i] = "<span class='mod'>#{aa}</span>" if i == m.location.to_i-1
end
end
and finally joined the array:
pep_seq_arr.join
It was easier than I first thought