Java searching for elements present in array - java

very new to java and oop in general. so be kind.
I have one text file which contains 10 integers, searchkeysArray.txt. The program creates an array named keysArr. I have another text file of 500 random integers, array1.txt. The program creates another array named array1.
I want to use the linearSearch method I created to search for the elements of keysArr within array1 and output the index which it exist.
public static int linearSearch(int arr[], int x)
{
int size = arr.length;
for(int i = 0; i < size; i++)
{
if(arr[i] == x)
return i;
}
return -1;
}
readFile method
public static int[] readFile(String file)
{
try {
File f = new File(file);
Scanner s = new Scanner(f);
int ctr = 0;
while (s.hasNextInt())
{
ctr++;
s.nextInt();
}
int[] arr = new int[ctr]; //create array of that size
Scanner scanner2 = new Scanner(f);
for (int i = 0; i < arr.length; i++)
arr[i] = scanner2.nextInt();
return arr;
}
catch(Exception e)
{
return null;
}
the program.
public static void main(String[] args)
{
int[] keysArr = readFile("searchkeysArray");
int[] array1 = readFile("array17");
int key = 34;
int result = linearSearch(array1, key);
if (result != -1)
System.out.print("The element " +key+" is present in the array, at index " + result + " ");
else
System.out.print("The element " +key+" is not present in the array ");
}
and it outputs
The element 34 is present in the array, at index 359
which makes sense. I've manually tested numbers and (apparently) everything works fine. But I do not quite understand how I'm supposed to use keysArr as my key rather than int x = some number.
Want to output something like
The element [keysArr[0]] is present in the array, at index 359
The element [keysArr[1]] is present in the array, at index 547
...
The element [keysArr[4]] is not present in the array
and so on.
Right now keysArr just an array of 10 integers but I will eventually use hundreds..

Rather than using a specific hard-coded key, such as int key = 34, you wish to loop over your array of keys keysArr. You can achieve that by using code like:
for (int key : keysArr) {
int result = linearSearch(array1, key);
if (result != -1)
System.out.print("The element " +key+" is present in the array, at index " + result + " ");
else
System.out.print("The element " +key+" is not present in the array ");
}

Your linear algorithm worth O(n^2) which is pretty bad if you are going to increase the number of integers.
I suggest you to load dictionary elements into a hash-map Value -> Index and iterate through the values array looking up for the position in the hashMap. This will give you O(2n) - the complexity will be linear. You'll require 2n of memory though. But in your case it is insignificant.
public static void main(String[] args) {
printResults(new int[]{1, 2, 3, 4}, new int[]{3, 4, 7, 9});
}
public static void printResults(int dictionary[], int valuesToSearch[]){
Map<Integer, Integer> positionsMap = new HashMap<>();
IntStream.range(0, dictionary.length).forEach(index -> positionsMap.put(dictionary[index], index));
Arrays.stream(valuesToSearch).mapToObj(value -> positionsMap.containsKey(value) ?
format("Value %s is present in the array at index %s", value, positionsMap.get(value)) : format("Value %s is not present in the array", value)
).forEach(System.out::println);
}

Related

What is wrong with my remove method for certain array integers?

I have to create a method that will remove at certain value from an array and create a new array without that certain value. For example, if my array is (0,2,3,5,3) and I want to remove 3, the new array should be (0,2,5). For some reason, it only works for the first two digits.
import java.util.Scanner;
public class removeDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
//array of numbers
int array[] = new int[] {0,1,2,3,4,5};
//invokes method and prints result
//System.out.println(remove(3,array));
remove(3,array);
}
//method remove that removes selected number from array
public static int[] remove(int v, int[] in) {
//count variable counts how many non-target numbers
int count = 0;
//for loop that checks if value at certain index is not equal to "v", the target number for removal
for(int k = 0; k < in.length; k++) {
//checks if certain number at certain index of array is not equal to v, or in this case, 3
if(in[k] != v) {
//counter
count++;
}
}
//new array that will stores values except "v"
int copy[] = new int[count];
//prints the length
System.out.println("array length: " + copy.length);
//for loop that checks if number not 3
for(int a = 1; a < in.length;) {
// sets number at certain index of main array into new array
if(in[a] != 3){
copy[a] = in[a];
a++;
System.out.println(copy[0]);
System.out.println(copy[1]);
System.out.println(copy[2]);
System.out.println(copy[3]);
}
else if(in[a] == 3) {
copy[a] = in[a+1];
}
}
//returns new array
return copy;
}
}
As said before, I need the new array to exclude the targeted number for removal.
You need two index variables for making the copy: one runs through the input array (a, as in the original code), and the other tracks your position in the output array (b, new variable). They can not be calculated from each other (they are the same at the beginning, but b can be significantly less than a at the end)
int b = 0;
for(int a = 0; a < in.length; a++) {
if(in[a] != v) {
copy[b] = in[a];
b++;
}
}
Using Java8 and it's streams feature you could do something like :
public static void main(String[] args) {
int[] array = {3236,47,34,34,73,46,3,64,473,4,4,346,4,63,644,4,6,4};
int[] newArray = removeAllOccurencesOf(array, 4);
System.out.println(Arrays.toString(newArray));
}
public static int[] removeAllOccurencesOf(int[] array, int numberToRemove)
{
//stream integers from array, filter the ones that correspond to number to remove, get what's left to new array
int[] newArray = IntStream.of(array).filter(i->i!=numberToRemove).toArray();
return newArray;
}
You can achieve the same result with some code like this:
// Add to params all inputs to remove from array
List<Integer> params = new ArrayList<>();
// Use Integer class instead of int datatype
Integer array[] = new Integer[] {0,1,2,3,4,3};
// Convert array to List class
List<Integer> list = new ArrayList<>(Arrays.asList(array));
// Remove all matches
list.removeAll(params);

Insert element in array - JAVA

WHY there is an ArrayIndexOutOfBounds Exception ..Please Clarify :)
I have tried changing the size of the array but still I am unable to create successful program
import java.util.Scanner;
class insert
{
public static void main(String[]args) throws Exception
{
Scanner sc = new Scanner(System.in);
int a[]= new int[5];
int i;
for(i=0;i<a.length-1;i++)
{
System.out.println("Enter the Element : ");
a[i]=sc.nextInt();
}
System.out.println("Enter the location for insertion : ");
int loc = sc.nextInt();
System.out.println("Enter the value for location : " +loc+" is");
int value = sc.nextInt();
for(i=a.length-1;i>loc;i--)
{
a[i+1]=a[i];
}
a[loc-1] = value;
System.out.println("New Array is : ");
for (i=0;i<=a.length-1;i++)
{
System.out.println(a[i]);
}
}
}strong text
In this part:
for(i=a.length-1;i>loc;i--)
{
a[i+1]=a[i];
}
On the first iteration, a[i+1] is the same as a[a.length], but the last element in array is a[a.length-1], becausefirst element is a[0] and last one is a[length-1], in total a.length number of elements. So modify your loop accordingly.
One side note, when you define a size of an array, you cannot change it. Size is immutable. So you cannot insert an element and try to shift all the elements, because you need to increase the size with 1, which is not possible.
For this scenario, use ArrayList<Integer>>. ArrayList size increases as you add new elements
It is this for loop throwing the RuntimeException
for(i=a.length-1;i>loc;i--) {
a[i+1]=a[i];
}
You are trying to set the value of i + 1 element of the array, which is not existing.
/* Inserting an element in an array using its Index */
import java.util.*;
public class HelloWorld{
public static void main(String []args){
int[] a = {1,2,3,4,5};
int[] b = new int[a.length + 1];
int index = 2;
int element = 100;
System.out.println("The original array is: "+ Arrays.toString(a));
// In this for loop we iterate the original array from the front
for (int i = 0; i<index; i++){
b[i] = a[i];
}
// Here we insert the element at the desired index
b[index] = element;
// In this for loop we start iterating the original array from back.
for (int i = a.length; i>index; i--){
b[i] = a[i-1];
// b[3] = a[2];
}
System.out.println("The new Array is: " + Arrays.toString(b));
}
}
Output:
The original array is: [1, 2, 3, 4, 5]
The new Array is: [1, 2, 100, 3, 4, 5]

How to check the object of type int[] of an arraylist?

I'm trying to find out particular elements in my ArrayList (arrayOne). Each element should be an int[]. I've tried System.out.println(arrayOne), which compiles but gives a irregular and strange number "[[I#370968]".
I've also tried System.out.println(arrayOne[0]) but it won't compile and emits the error
Array required but java.util.ArrayList found.
Given is the following code, with {1,12,3,13,123,2} passed to eg:
import java.util.ArrayList;
public class arrayTest {
private ArrayList<int[]> arrayOne;
public arrayTest(int[] eg) {
int[] xy = new int[2];
arrayOne = new ArrayList<int[]>(eg.length);
for (int i = 0; i < eg.length; i++) {
int sv = String.valueOf(eg[i]).length();
if (sv == 1) {
xy[0] = 0;
xy[1] = eg[i];
arrayOne.add(xy);
}
else if (sv == 2) {
System.out.println("two digits");
// TODO add code to make xy[0] = the first
// digit of eg and xy[1] = the second digit
}
else {
System.out.println("too many digits");
// and throw error accordingly
}
System.out.println(arrayOne);
}
}
}
How do make sure and print out the int array at arrayOne[0]
Given the code above if (sv == 2) and i want to split each individual number into an int[] with [0] being the first digit and [1] being the second digit how would i get the int value of each individual digit.
Use Arrays.toString(yourArray); to print out arrays in human readable form.
First of all, the string [I#370968 is displayed because you are trying to print an int[], which is actually an object. Because this object does not override the object's toString() method, that method is derived from the Object class. The Object.toString() implementation, which prints the class name (in this case [I, because it is an int array), then an # sign, and then the hash code of the object.
Your ArrayList contains a number of int[]s. Because an ArrayList is not an array (the one with the square brackets, like int[]), you can't call an element on it as if it were an array. In short, you cannot call arrayOne[someDesiredIndex].
In order to get an element from the ArrayList, call get(int index) on it; it returns the desired int[]. As already pointed out by another answer, you can use Arrays.toString(int[]) to print it in a human readable form.
To answer your questions:
You can retrieve the first index (0) of the first array inside arrayOne with the following code: arrayOne.get(0)[0].
The following code should work:
private static int[] intToArray(int n) {
String str = String.valueOf(n);
int length = str.length();
int[] ints = new int[length];
for (int i = 0; i < length; i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
return ints;
}
Above method puts each digit into the next array position (it also works with digits greater than 99). With this method you can easily get each individual digit:
int[] digits = intToArray(47);
int a = digits[0]; // Will be 4
int b = digits[1]; // Will be 7
So this is the class rewritten:
public class Rewrite {
private ArrayList<int[]> arrayOne = new ArrayList<int[]>();
public Rewrite(int[] eg) {
for (int i = 0; i < eg.length; i++) {
int length = String.valueOf(eg[i]).length();
switch (length) {
case 1:
this.arrayOne.add(new int[] { 0, eg[i] });
break;
case 2:
this.arrayOne.add(intToArray(eg[i]));
break;
default:
throw new IllegalArgumentException("Number " + eg[i] + " has too many digits");
// Or display the error or something.
}
System.out.println(Arrays.toString(this.arrayOne.get(i)));
}
}
private static int[] intToArray(int n) {
String str = String.valueOf(n);
int length = str.length();
int[] ints = new int[length];
for (int i = 0; i < length; i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
return ints;
}
public static void main(String[] args) {
Rewrite r = new Rewrite(new int[] { 47, 53, 91, 8 });
}

Return count of values in array not divisible evenly by 2

I've got an random array generated and I need a way to return the index of value of user input. So if it gives 8 random numbers, it then asks user to find a value in array.. Once that value is entered it needs to return the first index of that value. We haven't gone over this much in class and I don't know the best way to return this. Here's what I have so far:
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer to find in the array:");
int target = input.nextInt();
// Find the index of target in the generated array.
/*
** 3. write findValue **
*/
int index = findValue(array, target);
if (index == -1)
{
// target was not found
System.out.println("value " + target + " not found");
}
else
{
// target was found
System.out.println("value " + target + " found at index " + index);
}
}
/*
allocate a random int[] array with size elements, fill with
random values between 0 and 100
*/
public static int[] generateRandomArray(int size)
{
// this is the array we are going to fill up with random stuff
int[] rval = new int[size];
Random rand = new Random();
for (int i=0; i<rval.length; i++)
{
rval[i] = rand.nextInt(100);
}
return rval;
}
/*
print out the contents of array on one line, separated by delim
*/
public static void printArray(int[] array, String delim)
{
// your code goes here
System.out.println (Arrays.toString(array));
}
/*
return the count of values in array that are not divisible evenly by 2
*/
public static int countOdds(int[] array)
{
int count=0;
// your code goes here
for (int i=0; i<array.length; i++){
if (array[i] %2 !=0) {
count++;
}
}
return count;
}
/*
return the first index of value in array. Return -1 if value is not present.
*/
public static int findValue(int[] array, int value)
{
// your code goes here
return -1;
}
}
First of all, please fix your question title.
And now to the solution. How would you do that in real life? You would go through the array and check every single entry if it matches the searched value.
And thats exactly how you can do this in Java.
public static int findValue(int[] array, int value) {
for (int i = 0; i < array.length; i++) { // iterate over the content of the given array
if (array[i] == value) { // check if the current entry matches the searched value
return i; // if it does return the index of the entry
}
}
return -1; // value not found, return -1
}
Here is an example for calling this method:
public static void main(String[] args) {
int[] array = new int[] { 1, 2, 3, 4, 5, 6 };
System.out.println(findValue(array, 6));
}
This will print 5, because the number 6 is on the 5th position in the given array. Keep in mind that the index starts with 0.

Count how many times an element occurs in an array - Java

I recently made a very simple practice program in Python, that takes user input and rolls dice. The code is:
import random
import sys
import math
def roll(rolls, sides, results):
for rolls in range(1, rolls + 1):
result = random.randrange(1, sides + 1)
print result
results.append(result)
def countf(rolls, sides, results):
i = 1
print "There were", rolls, "rolls."
for sides in range(1, sides + 1):
if results.count(i) != 1:
print "There were", results.count(i), i,"s."
else:
print "There was", results.count(i), i
i = i + 1
if i == sides:
break
rolls = input("How many rolls? ")
sides = input("How many sides of the die? ")
results = []
roll(rolls, sides, results)
countf(rolls, sides, results)
(actually this is part of a larger program, so I had to cut'n'paste bits, and I might have missed something out).
And so I decided to translate that to Java. Notice the algorithm here: get random number, print it, append it to an array, then count the amount of each number in the array at the end, and print out that value. Problem is, I don't know how to do the equivalent of someArray.count(someIndex) in Java syntax. So my Java program looks like this so far:
import java.util.*;
public class Dice {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random();
int[] results = new int[TIMES_TO_ROLL];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt(6);
System.out.println(result);
results[i] = result;
}
}
public static int getInt(String prompt) {
System.out.print(prompt + " ");
int integer = input.nextInt();
input.nextLine();
return integer;
}
}
So can someone help me with the array counting code? I understand that this might not be a defined method, since Python is higher level after all, so I could make my own array counting method, but I was wondering if Java, like Python, has a predefined one.
EDIT: I managed something like this:
public static int arrayCount(int[] array, int item) {
int amt = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == item) {
amt++;
}
else {
amt = amt;
}
}
return amt;
}
EDIT: Just out of interest, assuming I use Command prompt to run my Java program and Python.exe (command prompt console for Python), which one will be faster (in other words, for the same code, which language has better performance?)?
You could use a HashMap to store the result.
If the new number is not in your map you add it with "1" as initial value.
If it exists your put "+1" to the current map value.
To display the values you just have to iterate on you entries in a for each loop.
The solution is to transform your array to a List and then use the Collections.frequency method:
List<Integer> resultList = Arrays.asList(results);
int freq = Collections.frequency(resultList, 4);
Also you could use ArrayList from the very beginning saving you the transformation:
List<Integer> result = new ArrayList<Integer>();
// add results
int freq = Collections.frequency(result, 4);
See the Collections documentation here
EDIT: If performance is an issue (as suggested in the comments) then maybe you want to use each index of the array as a counter, as follows:
Random flip = new Random(SIDES);
int[] counters = new int[SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
counters[result] = counters[result]+1;
}
Notice that you no longer need to count at the end since you've already got all the counters in the array and there is no overhead of calculating the hash.
There are a couple libraries that will do this for you:
Google Guava's MultiSet
Apache Common's Bag
But for something so simple, you may consider an extra library a bit excessive.
You can also do this yourself with an int[]. Assuming your dice is using whole numbers, have the number rolled refer to the index into the array, and then increment the value at that index. When you need to retrieve the value for a given number, look up its value by the index.
private static final int NUMBER_DICE_SIDES = 6;
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random(NUMBER_DICE_SIDES);
int[] results = new int[NUMBER_DICE_SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
System.out.println(result);
results[result]++;
}
for(int i = 0; i < NUMBER_DICE_SIDES; ++i) {
System.out.println((i+1)+"'s: " + arraysCount(results, i));
}
}
public static int arrayCount(int[] array, int item) {
return array[item];
}
There's a frequency method in collections
int occurrences = Collections.frequency(listObject, searchItem);
Java doc for collections
As far as I am aware, there is no defined method to return the frequency of a particular element in an array. If you were to write a custom method, it would simply be a matter of iterating through the array, checking each value, and if the value matches the element you're after, incrementing a counter.
So something like:
// in this example, we assume myArray is an array of ints
private int count( int[] myArray, int targetValue) {
int counter = 0;
for (int i = 0 ; i < myArray.length; i++ ) {
if (myArray[i] == targetValue) {
counter++;
}
}
return counter;
}
Of course, if you want to find the frequency of all the unique values in your array, this has the potential of being extremely inefficient.
Also, why are you using a 7-sided die? The Random nextInt() will return a number from 0 up to but not including the max. So your die will return values from 0 through 6. For a six-sided die, you'd want a new Random(6); and then increment your roll by one to get a value from one through six: flip.nextInt() +1;.
class FindOccurrence {
public static void main (String[]args) {
int myArray[] = {5, 8, 5, 12, 19, 5, 6, 7, 100, 5, 45, 6, 5, 5, 5};
int numToFind = 5;
int numberOfOccurrence = 0;
for (int i=0; i < myArray.length; i++) {
if (numToFind == myArray[i]) {
numberOfOccurrence++;
}
}
System.out.println("Our number: " + numToFind);
System.out.println("Number of times it appears: " + numberOfOccurrence);
}
}

Categories