I want to search or select specific itmes from a list/array. So on constructing the function for searching in AS3 in flash, I got stuck..Please help to solve this problem...Thanks in advance
var ar:Array = new Array();
ar=[ "bhati", "malav", "vinod"];
//Searching Function
function findIndexOfValue( array:Array, _value:* ):int {
var _length:uint = array.length;
for(var i:uint=0; i < _length; i++) {
if(array[i] == _value) {
return i;
}
else{
return -1;
}
}
}
trace(findInndexOfValue( ar, "bhati" )); // it should output 0 .
//compiler error:- 1170:Function doesn't return a value., I tried my best, but unable to solve this.
How about
function findIndexOfValue( array:Array, _value:* ):int {
var _length:uint = array.length;
for(var i:uint=0; i < _length; i++) {
if(array[i] == _value) {
return i;
}
}
return -1;
}
Why bother with this? This functionality is built right into the Array class in AS3 (And most, if not all, OOP languages).
trace( this.ar.indexOf( "bhati" ) ); //will output 0
Array#indexOf()
As to why your script doesn't work, you have to return a value. You can't have all the returns in conditionals or loops. There must be a return in within the base level of the function.
EDIT: Just took a closer look at your function and there is more wrong with it than just the return. You will never make it beyond the first item in the array because it will always return a value (thanks to the else conditional). Simply remove the else bit and move the return in it to after the for loop runs and you will have a rough duplication of how indexOf works
Related
I have a piece of code that I need insight on, I don't want to know the correct solution of the problem. I just want to know why is my concept failing.
So the function is to check if a binary tree is BST or not. I need to return 1 in case it is and 0 otherwise. My code is as below
int isBST(Node root) {
if(root == null)
return 1;
if(root.left!=null) {
if(root.left.data<root.data)
isBST(root.left);
else
return 0; // line:a
}
if(root.right!=null) {
if(root.right.data<root.data)
isBST(root.right);
else
return 0;
}
return 1;
}
For this piece, when i have a binary tree as follows:
5
\
7
/
8
I expect it to reach 8 value and break at line:a but it return me 1 instead of 0. Now I know 0 gets returned to the parent calling method. But is it not terminating because I have made isBST call without capturing the return value?
Please dont point out if there are anyother bugs.
For the general case, your approach won't work. The way to test if a tree is a BST is to recursively check if the current node is greater than the maximum element of the left subtree, and smaller than the minimum element of the right subtree. Also, you're missing the returns in the recursive calls:
return isBST(root.left);
...
return isBST(root.right);
By the way, why are you returning 0 or 1 for this? use false or true instead, changing the return type to boolean.
You should check if the right data ist bigger than the current and return the value of the recursive call
if(root.right.data>root.data)
I see the following issues:
If (and only if) isBST(root.left) or isBST(root.right) is false, you need to return 0 (btw, why are you not using booleans?) immediately.
The condition root.right.data<root.data should be inverted: root.right.data>=root.data.
So here's the modified code (keeping the int return type):
int isBST(Node root) {
if(root == null)
return 1;
if(root.left!=null) {
if(root.left.data<root.data) {
if (isBST(root.left) == 0)
return 0;
} else
return 0;
}
if(root.right!=null) {
if(root.right.data>=root.data) {
if (isBST(root.right) == 0) {
return 0;
}
} else
return 0;
}
return 1;
}
I came across the following question in Cracking the Coding Interview, 1.1:
Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?
Here is the book's solution:
Here is my solution:
public boolean allUnique(String input) {
HashSet<Character> set = new Hashset<Character>();
char c;
for (int i = 0; i < input.length(); i++) {
c = input.charAt(i);
if (set.contains(c)) return false;
set.add(c);
}
return true;
Does my solution work, and how efficient is it? I was also wondering if someone could explain ASCII and how it is relevant to this problem, since it was briefly mentioned in the book's solution. Is this why we are able to type-cast each char in the String to an integer?
Thank you!
To show how not to use an array (unknown if this is really fast or not) you can:
function boolean allUnique(String input){
for( int i=0; i<input.length(); i++ ){
if( input.indexOf(input.charAt(i),i) > -1 ){ return false; }
}
return true;
}
The above is not tested, but should work. The ",i)" may need to be ",i+1)" to put it past the current character. But I think just ",i)" should work.
I have some code that I would like to make more efficient by recursion. Trouble is I don't know where to start. The code compares two arraylists a and b to see if they are equal. Assume the sizes of both arrays are equal.
The code is
public boolean isEqual(A B) {
boolean answer = false;
if (lessThanOrEqualTo(B) == true);
for (int i = 0; i < DList.size(); i++) {
if (DList.get(i) == B.DList.get(i)) answer = true;
else answer = false;
}
return answer;
}
I have currently written
public boolean isEqualRecursion(A B) {
if DList.size() == 0;
return false();
} else {
}
I know the stopping case is 0 as when size is 0 nothing happens. I have no idea what to write next
Any help will be appreciated
Thanks
I have some code that I would like to make more efficient by recursion.
It is unlikely that you can make it more efficient by recursion. The chances are that it will be less efficient, and also fragile. This is because standard Java compilers don't implement tail-call optimization. The fragility occurs because a recursive comparison algorithm is liable to trigger a stack overflow if the input arrays are large enough.
However, if you want to continue with this as "an exercise", then my HINT is to add an index argument to the isEqualRecursion signature ...
I think that this is a pretty good start for you. This looks through all your elements, assuming they are an array, and then checks if they are equal in size.
public boolean isEqual(ArrayList<?> a, ArrayList<?> b) {
if (a.size() != b.size())
return false;
for (int i = 0; i < a.size(); i++) {
if (!isEqual((ArrayList<?>)a.get(i), (ArrayList<?>)b.get(i))) {
return false;
}
}
return true;
}
Now a couple of things to consider:
This assumes that the content of a(and b) must be an ArrayList at line (ArrayList<?>)a.get(i) what if our ArrayList actually contains something else, like an Integer?
What if our array lists contain null as an item?
What if we pass in two null ArrayLists? (or even just one?)
I'm not sure the point of your function lessThanOrEqualTo(B) is this part of the question or did you write this down wrong?
Also what is a DList?
This is a typical recursion question. You might want to try something like this:
int x = 0;
if(Dlist.get(x) != B.Dlist.get(x)) {
return false;
} else {
x+1;
}
if( x!= dList.size()) {
recursion;
}
return true;
Here's what I'm trying to implement:
"If the strand is:
AACATGTACTACTGGTG
and the snip method is called like this:
snip("CA", "A")
then the resulting new DNAStrandJedi object should represent the
strand "TGT" which is found after the first match of "CA" at index 2
and before the subsequent match of "A" at index 7."
And here's my code:
public DNAStrandJedi snip(String startPattern, String endPattern) {
if (!passedStrand.contains(startPattern)
|| !passedStrand.contains(endPattern)) {
return null;
} else {
String snippedString = passedStrand.substring(3, 5);
return new DNAStrandJedi(snippedString);
}
}
The strand that I'm trying to snip is: "AGTCAGTACC"
Here I'm printing the results of the snip() method to the console:
System.out.println("Snip: " + test.snip("GT", "TA").getStrandString());
I should be getting the strand "CAG" but instead I'm just getting CA.
What I'm having trouble with is figuring out the numbers to use as indices to get the snippedString. Would I have to use some sort of for loop here to get the indices of the startPattern and endPattern? Let me know if you find the question confusing and I'll try to explain it better.
The String.indexOf() function is what you need.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String, int)
if (passedStrand.indexOf(startPattern) > -1 && passedString.indexOf(endPattern, passedStrand.indexOf(startPattern)) > -1)
return return new DNAStrandJedi(passedStrand.indexOf(startPattern)+startPattern.length, passedString.indexOf(endPattern, passedStrand.indexOf(startPattern))-1);
else
return null;
(not tested and not optimal, but its something similar)
The code below is written in simple and clear way and it might explain
public DNAStrandJedi snip(String startPattern, String endPattern) {
int sL = startPattern.length();
int startIndex = passedStrand.indexOf(startPattern);
int endIndex = passedStrand.indexOf(endPattern, startIndex + sL);
if ( startIndex == -1 || endIndex == -1 )
return null;
}
String snippedString = passedStrand.substring(startIndex+sL, endIndex);
return new DNAStrandJedi(snippedString);
}
For the information of Java String Functions you can see at here
Actually #vanza appears to have answered your question it's the "substring(3,5)" that is hard coded that is causing the problem.
You reference a "passedStrand" variable, but you don't show how it is initialized...Did you maybe miss something that's related that we need to know to help you solve the problem?
Use indexOf to find the indices...
} else {
int start = passedStrand.indexOf(startPattern) + startPattern.length();
int end = passedStrand.indexOf(endPattern, start);
String snippedString = passedStrand.substring(start,end);
return new DNAStrandJedi(snippedString);
}
this is my first question on stack overflow but I have some experience in Java. I am making a Java application at the moment (575 lines and counting!) and am trying to search through an ArrayList for a string. But I do not want it to be exact! Let me clarify: I want to iterate through each ArrayList element and search that string for another string. if the string is found in the ArrayList element, (for now) I want it printed to the console. I hope I have been clear enough.
Following is the relevant code. All variables are defined and the code compiles, just no output (from the search function) is printed. I am pretty sure that it is because the for loop doesn't execute, but I am puzzled as to why.
//the keylistener that calls the search() function, attached to a JTextField that the query is entered into
class searchFieldListener implements KeyListener {
searchFieldListener() {
}
public void keyTyped(KeyEvent event) {
if (event.getID() == KeyEvent.KEY_TYPED) {
query = searchField.getText()+Character.toString(event.getKeyChar());
System.out.println(query);
for (i = 0; i == nameList.size(); i++) {
search(query, i);
}
}
}
public void keyReleased(KeyEvent event) {
}
public void keyPressed(KeyEvent event) {
}
}
//the troublesome search() function
void search(String query, int iter) {
searchString = nameList.get(iter);
System.out.println(searchString);
if (searchString.indexOf(query) != -1) {
System.out.println(Integer.toString(iter));
} else {
System.out.println("not found \n");
}
}
Variables/Objects and uses:
searchFieldListener
The KeyListener for the JTextField called searchField for obvious reasons.
query
The string of the text to be searched for.
i
Why does everyone use i in loops? I guess it's a coding tradition.
nameList
The ArrayList of names (well, duh).
searchString
The string to be searched in (as in, try to find query in searchString).
iter
The number of iterations the for loop has been through so far.
Once again I hope I have been clear enough. Thanks!
The reason why your for loop is not executing is because of the condition used in the loop:
for (i = 0; i == nameList.size(); i++)
^^
Since the size method of the ArrayList class returns the number of elements you might want to have
i < nameList.size() instead.
for (i = 0; i == nameList.size(); i++)
should be
for (i = 0; i < nameList.size(); i++)
Not sure if you need < or <= though, you just modify it to you needs.
have have a typo in your for-loop. shouldn't this:
for (i = 0; i == nameList.size(); i++) {
look like this:
for (i = 0; i < nameList.size(); i++) {
Several correct answers, but one aspect is missing:
for (i = 0; i < nameList.size(); i++)
This is an old-school loop. Starting from Java 1.5, you should use this idiom to iterate over an array or iterable (a List is an Iterable):
for(String s: strings){
}
This simpler syntax is a) much less error-prone and b) a common way to iterate over many different data structures, including arrays and collections.
Internally this is a shortcut for this code:
for(Iterator<String> it = strings.iterator(); it.hasNext();){
String s = it.next();
// your code here
}