Recursive Search Function Java - java

public int search(String type) {
for (int i = 0; i < size; i++) {
if (array[size-1-i].contains(type)) return i;
}
return -1;
}
I am having trouble doing a recursive function of this previous search function , can somebody help me ?

For a recursive function, a simple solution would be to pass in the value you want to search and the index to search at as parameters to the function.
Then you check
if the index passed in is greater than length of array , then return -1 (since we were not able to find the element.
if you can find the value pass in at the index passed in, if yes, just return that index ,
if not above 2 , then try to search it at next index.
For this recursive function, start at index 0 , by passing 0 when calling the function.
Example code -
public int search(String type, int index) {
if (index >= array.length) {
return -1;
}
else if(array[index].contains(type)) {
return array.length - i + 1; # assuming size from your function is array.length
}
else {
return search(type, index + 1)
}
}

It seems you want to write a recursive variant of this search function. I am not doing any optimization in your code as you need to take care of that. I have assumed few things to make your code compile and here is the code I have tried:
static String[] array = new String[] {"John", "Sam", "David"};
static int size = array.length;
public static void main(String[] args) {
int index = searchRecursive(0,"Sam");
System.out.println("Index: " + index);
}
public static int searchRecursive(int indexToCheck, String type) {
int result = -1;
if(indexToCheck<size) {
if(array[size-1-indexToCheck].contains(type)) {
result = indexToCheck;
} else {
result = searchRecursive(indexToCheck+1,type);
}
}
return result;
}
public static int searchIterative(String type) {
for (int i = 0; i < size; i++) {
if (array[size-1-i].contains(type)) return i;
}
return -1;
}

Related

Given an array of strings, write a recursive method that searches for a given string in O(n) and returns the index. LMK how to fix error

//this is the method to get the first string in the arraylist
public static Integer findFirstString(ArrayList<String> arrayOfStrings, String stringToFind) {
if (arrayOfStrings.isEmpty()) {
return -1;
}
if (arrayOfStrings.get(0).equals(stringToFind)) {
return 0;
}
//int index = 0;
//Error is line below this
Integer resultArray = findFirstString(arrayOfStrings.get(index), stringToFind);
if (resultArray == -1) {
return resultArray;
}
else {
return resultArray + 1;
}
}
I need help fixing the get(index) part, I'm not sure if initializing it helps or if it is completely incorrect.
In you code your method
findFirstString(ArrayList<String> arrayOfStrings, ....
is expecting an ArrayList, but when you can it as
findFirstString(arrayOfStrings.get(index)...
the method
arrayOfStrings.get(index)
only returns one Object.
Consider change your method so that it passing in an index which should be used like (not tested)
public static Integer findFirstString(ArrayList<String> arrayOfStrings, String stringToFind,
int index) {
if (arrayOfStrings.isEmpty()) {
return -1;
}
if (arrayOfStrings.get(index).equals(stringToFind)) {
return 0;
}
return findFirstString(arrayOfStrings, stringToFind, index++);
}

how to count many times a character occurs in a string without using s loop

the code below is meant to count each time character 'x' occurs in a string but it only counts once ..
I do not want to use a loop.
public class recursionJava
{
public static void main(String args[])
{
String names = "xxhixx";
int result = number(names);
System.out.println("number of x: " + result);
}
public static int number (String name)
{
int index = 0, result = 0;
if(name.charAt(index) == 'x')
{
result++;
}
else
{
result = result;
}
index++;
if (name.trim().length() != 0)
{
number(name);
}
return result;
}
}
You could do a replacement/removal of the character and then compare the length of the resulting string:
String names = "xxhixx";
int numX = names.length() - names.replace("x", "").length(); // numX == 4
If you don't want to use a loop, you can use recursion:
public static int number (String name)
{
if (name.length () == 0)
return 0;
int count = name.charAt(0)=='x' ? 1 : 0;
return count + number(name.substring(1));
}
As of Java 8 you can use streams:
"xxhixx".chars().filter(c -> ((char)c)=='x').count()
Previous recursive answer (from Eran) is correct, although it has quadratic complexity in new java versions (substring copies string internally). It can be linear one:
public static int number(String names, int position) {
if (position >= names.length()) {
return 0;
}
int count = number(names, position + 1);
if ('x' == names.charAt(position)) {
count++;
}
return count;
}
Your code does not work because of two things:
Every time you're calling your recursive method number(), you're setting your variables index and result back to zero. So, the program will always be stuck on the first letter and also reset the record of the number of x's it has found so far.
Also, name.trim() is pretty much useless here, because this method only removes whitespace characters such as space, tab etc.
You can solve both of these problems by
making index and result global variables and
using index to check whether or not you have reached the end of the String.
So in the end, a slightly modified (and working) Version of your code would look like this:
public class recursionJava {
private static int index = 0;
private static int result = 0;
public static void main(String[] args) {
String names = "xxhixx";
int result = number(names);
System.out.println("number of x: " + result);
}
public static int number (String name){
if(name.charAt(index) == 'x')
result++;
index++;
if(name.length() - index > 0)
number(name);
return result;
}
}
You can use StringUtils.countMatches
StringUtils.countMatches(name, "x");

Searching for specific value in array with while-loop

I have the task to build a method to search for an identical value for a variable in an array.
When there is a match, the method will return the index-Position, otherwise it should return -1.
My method works when there is a match, but I get an error when there isn´t any match.
My Code so far:
public class Schleifentest {
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] cherry = {7,5,6,8,9};
int magNumber = 112;
int enthalten2 = Schleifentest.sucheWhile(cherry, magNumber);
System.out.println(enthalten2);
}
public static int sucheWhile(int [] array, int a) {
int i = 0;
while(i <= array.length) {
if (array[i] == a) {
return i;
}
i++;
}
// here is the problem
return -1;
}
}
Thanks for your help.
Phil
it should be
while(i < array.length) {...}
suppose that the array has 10 elements. They are indexed from 0 to 9. When you reach the end, with your code, you'll consider the one indexed as 10, that doesn't exist, and you have the error.

How to find index of STRING array in Java from a given value?

I wanted to know if there's a native method in array for Java to get the index of the table for a given value ?
Let's say my table contains these strings :
public static final String[] TYPES = {
"Sedan",
"Compact",
"Roadster",
"Minivan",
"SUV",
"Convertible",
"Cargo",
"Others"
};
Let's say the user has to enter the type of car and that then in the background the program takes that string and get's it's position in the array.
So if the person enters : Sedan
It should take the position 0 and store's it in the object of Cars created by my program ...
Type in:
Arrays.asList(TYPES).indexOf("Sedan");
String carName = // insert code here
int index = -1;
for (int i=0;i<TYPES.length;i++) {
if (TYPES[i].equals(carName)) {
index = i;
break;
}
}
After this index is the array index of your car, or -1 if it doesn't exist.
for (int i = 0; i < Types.length; i++) {
if(TYPES[i].equals(userString)){
return i;
}
}
return -1;//not found
You can do this too:
return Arrays.asList(Types).indexOf(userSTring);
I had an array of all English words. My array has unique items. But using…
Arrays.asList(TYPES).indexOf(myString);
…always gave me indexOutOfBoundException.
So, I tried:
Arrays.asList(TYPES).lastIndexOf(myString);
And, it worked. If your arrays don't have same item twice, you can use:
Arrays.asList(TYPES).lastIndexOf(myString);
try this instead
org.apache.commons.lang.ArrayUtils.indexOf(array, value);
Use Arrays class to do this
Arrays.sort(TYPES);
int index = Arrays.binarySearch(TYPES, "Sedan");
No built-in method. But you can implement one easily:
public static int getIndexOf(String[] strings, String item) {
for (int i = 0; i < strings.length; i++) {
if (item.equals(strings[i])) return i;
}
return -1;
}
There is no native indexof method in java arrays.You will need to write your own method for this.
An easy way would be to iterate over the items in the array in a loop.
for (var i = 0; i < arrayLength; i++) {
// (string) Compare the given string with myArray[i]
// if it matches store/save i and exit the loop.
}
There would definitely be better ways but for small number of items this should be blazing fast. Btw this is javascript but same method should work in almost every programming language.
Try this Function :
public int indexOfArray(String input){
for(int i=0;i<TYPES,length();i++)
{
if(TYPES[i].equals(input))
{
return i ;
}
}
return -1 // if the text not found the function return -1
}
Testable mockable interafce
public interface IArrayUtility<T> {
int find(T[] list, T item);
}
implementation
public class ArrayUtility<T> implements IArrayUtility<T> {
#Override
public int find(T[] array, T search) {
if(array == null || array.length == 0 || search == null) {
return -1;
}
int position = 0;
for(T item : array) {
if(item.equals(search)) {
return position;
} else {
++position;
}
}
return -1;
}
}
Test
#Test
public void testArrayUtilityFindForExistentItemReturnsPosition() {
// Arrange
String search = "bus";
String[] array = {"car", search, "motorbike"};
// Act
int position = arrayUtility.find(array, search);
// Assert
Assert.assertEquals(position, 1);
}
Use this as a method with x being any number initially.
The string y being passed in by console and v is the array to search!
public static int getIndex(int x, String y, String[]v){
for(int m = 0; m < v.length; m++){
if (v[m].equalsIgnoreCase(y)){
x = m;
}
}
return x;
}
Refactoring the above methods and showing with the use:
private String[] languages = {"pt", "en", "es"};
private Integer indexOf(String[] arr, String str){
for (int i = 0; i < arr.length; i++)
if(arr[i].equals(str)) return i;
return -1;
}
indexOf(languages, "en")

Gets the index of the first String that starts with the target - give wrong output

This method should return the index of the first string that starts with the target.
Return -1 if no string starts with the target.
My implementations works but not covers all variations.
Code:
public int getIndex(ArrayList<String> text, String target)
{
int i = 0;
int index = -1;
boolean found = false;
while (!found && i < text.size()) //supply condition
{
for (String s : text) {
if (s.contains(target)) {
found = true;
} else {
i++;
}
if (found) index = i;
}
}
return index;
}
testing part:
public static void main(String[] args)
{
ArrayList<String> cities = new ArrayList<String>();
cities.add("Chicago");
cities.add("Houston");
cities.add("San Jose");
cities.add("Seattle");
cities.add("Denver");
Finder finder = new Finder();
System.out.println(finder.getIndex(cities, "C"));
System.out.println("Expected: 0");
System.out.println(finder.getIndex(cities, "S"));
System.out.println("Expected: 2");
System.out.println(finder.getIndex(cities, "D"));
System.out.println("Expected: 4");
System.out.println(finder.getIndex(cities, "X"));
System.out.println("Expected: -1");
}
This code has coverage 50/50 input:
4
- Expected: 0
3
- Expected: 2
4
+ Expected: 4
-1
+ Expected: -1
How to solve this issue?
You claim:
My implementations works
It doesn't look like it to me, based on the tests. Your code is much more complicated than it needs to be, which is making it hard to find the bug. The problem is that you've got two loops for no reason:
while (!found && i < text.size()) //supply condition
{
for (String s : text) {
}
}
Why have you got both of those loops? You're incrementing i multiple times within the inner loop...
You'd probably find it easier to get all the tests to pass if you simplify it:
public int getIndex(List<String> text, String target) {
for (int i = 0; i < text.size(); i++) {
if (text.get(i).startsWith(target)) {
return i;
}
}
return -1;
}
This is one of those cases where a dogmatic insistence on only having one return statement per method leads to much messier code.
Note that I've changed the condition from contains (in your code) to startsWith to match the description. You should add a test for this difference - try to find a string which is present in one of the cities, but the city doesn't start with that value.
I've also changed the parameter type to List<String> as you don't really need it to be an ArrayList<String>. (With a bit of work you could make it accept Iterable<String> instead, but that would be more complicated.)
I'd also recommend that you start using JUnit or something similar for your testing, rather than just using System.out.println.
EDIT: Just for a bit of fun, a version which takes Iterable<String> and uses that to handle even LinkedList<String> efficiently:
public int getIndex(Iterable<String> elements, String target) {
int index = 0;
for (String element : elements) {
if (element.startsWith(target)) {
return index;
}
index++;
}
return -1;
}
(Not that much harder after all...)
public int getIndex(ArrayList<String> text, String target)
{
for(int i=0;i < text.size();i++)
{
if(text.get(i).indexOf(target) == 0)
return i;
}
return -1;
}
Making the following changes:
Get rid of unnecessary found variable
Replace contains with startsWith
Remove the for-loop, otherwise you pass through the data a few times
Change the while-loop to a for-loop
I get to this, which seems to work:
public int getIndex(ArrayList<String> text, String target)
{
int index = -1;
for (int i = 0; index == -1 && i < text.size(); i++)
{
if (text.get(i).startsWith(target))
{
index = i;
}
}
return index;
}
You can of course improve on it a lot more still.
Change the getIndex method with this:
public int getIndex(ArrayList<String> text, String target)
{
int i = 0;
for (String s : text) {
// Use startsWith if you want to check if the string starts with target...
// Use contains if you want to check if contains target...
if (s.startsWith(target)) {
return i;
}
i++;
}
return -1;
}

Categories

Resources