Finding the occurrence of values within an array - java

My question is how do I find the frequency of the numbers "8" and "88" in this array, using a method. It seems as what I put in the assessor method does not appear to work. For example, if "8" occurs three times in the array the output would be "3" and the same for "88".
If I am wrong please point me to the right direction. Any help with my question is greatly appreciate.
import java.util.Random;
public class ArrayPractice {
private int[] arr;
private final int MAX_ARRAY_SIZE = 300;
private final int MAX_VALUE = 100;
public ArrayPractice() {
// initialize array
arr = new int[MAX_ARRAY_SIZE];
// randomly fill array with numbers
Random rand = new Random(1234567890);
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
arr[i] = rand.nextInt(MAX_VALUE) + 1;
}
}
public void printArray() {
for (int i = 0; i < MAX_ARRAY_SIZE; ++i)
System.out.println(arr[i]);
}
public int countFrequency(int value) {
for (int i: MAX_VALUE) {
if (i == 8)
i++;
}
public static void main(String[] args) {
ArrayPractice ap = new ArrayPractice();
System.out.println("The contents of my array are: ");
ap.printArray();
System.out.println("");
System.out.println("The frequency of 8 is: " + ap.countFrequency(8));
System.out.println("The frequency of 88 is: " + ap.countFrequency(88));
}
}
}

You need to iterate over arr and increment a variable when an element matches value.
public int countFrequency(int value) {
int count = 0;
for (int num : arr) {
if (num == value) {
count++;
}
}
return count;
}

You have a hard-coded seed, so your random values won't be random on different runs. You are also hard-coding your frequency count against 8 (instead of value). But honestly, I suggest you revisit this code with lambdas (as of Java 8), they make it possible to write the array generation, the print and the count routines in much less code. Like,
public class ArrayPractice {
private int[] arr;
private final int MAX_ARRAY_SIZE = 300;
private final int MAX_VALUE = 100;
public ArrayPractice() {
// randomly fill array with numbers
Random rand = new Random();
arr = IntStream.generate(() -> rand.nextInt(MAX_VALUE) + 1)
.limit(MAX_ARRAY_SIZE).toArray();
}
public void printArray() {
IntStream.of(arr).forEachOrdered(System.out::println);
}
public int countFrequency(int value) {
return (int) IntStream.of(arr).filter(i -> i == value).count();
}
}

You need to iterate over the array and increment a counter variable when an element matches i
what you are doing is increment i instead of a counter:
if (i == 8)
i++;
} // if i is 8 then i becomes 9
A working example:
public int countFrequency(int i) {
int count = 0;
for (int num : arr) {
if (num == i) {
count++;
}
}
return count;
}

Solution:
public int countFrequency(int value) {
int counter = 0; // here you will store counter of occurences of value passed as argument
for (int i : arr) { // for each int from arr (here was one of your errors)
if (i == value) // check if currently iterated int is equal to value passed as argument
counter++; // if it is equal, increment the counter value
}
return counter; // return the result value stored in counter
}
Explanation:
Main problem in your code was countFrequency() method, there are few bugs that you need to change if you want to make it work correctly:
You passed value as argument and you didn't even use it in the body of method.
for (int i : MAX_VALUE ) - you meant to iterate over elements of arr array, (You can read it then as: For each int from arr array do the following: {...}.
if (i == 8) i++ - here you said something like this: Check if the current element from array (assuming that you meant MAX_VALUE is an array) is equal to 8, and if it is - increment this value by 1 (so if it were 8, now it's 9). Your intention here was to increment counter that counts occurences of 8.
You might want to consider making these improvements to countFrequency() method, to make it work properly.

Related

How do I rerun a static integer array?

here's the array I want to rerun:
public static int[] rollDice(int dice[]) {
// generate 5 random numbers / update dice array
for (int i = 0; i < dice.length; i++) {
dice[i] = (int)(Math.random() * 6 + 1);
}
return dice;
}
If I want to reset this array and find new random numbers how would I do that? I tried rollDice() only to get an error.
There is no point in returning the array, since you already have a reference to the array when you call the method rollDice().
Arrays are sent by reference and not by value, which means you are not working with a copy like you do with ints, instead you are modifing the original array.
Change the return type to void and remove the return and your code should work as intended.
You can get every time a new dynamic length array with random numbers, and you can access by call rollDice(integer value).
public static int[] rollDice(int length) {
final int dice[] = new int [length];
// generate array with random values
for (int i = 0; i < length; i++) {
dice[i] = (int)(Math.random() * length + 1);
}
return dice;
}
You would have to have a class member like this:
public static final int[] dice = new int[5];
Then to roll/reroll the dice use your method, else just access dice.
public static void rollDice() {
// generate 5 random numbers / update dice array
for (int i = 0; i < dice.length; i++) {
dice[i] = (int)(Math.random() * 6 + 1);
}
}
Interesting fact: Java has no static function variables as C and C++ does. In those languages it could look like this:
(I wrote it like a java Function for you Java guys)
public static int[5] rollDice(boolean reroll) {
static final int[] dice = new int[5];
if (reroll) for (int i = 0; i < dice.length; i++) {
dice[i] = (int)(Math.random() * 6 + 1);
}
return dice;
}
As you can see, static variables can be embedded into those functions. If you ask me, it's a huge minus, Java doesn't support this as I use it all the time to hide those from the class namespace.

what is wrong with the logic of my method to add the odd numbers of an array

I am trying to write a method that will take in the array int[] numbers and return the sum of all of the odd numbers in the array. I am not sure why it is not returning the correct value. Currently it returns "3" when it should be returning "9".
public static void main(String[] args) {
int[] numbers = { 2, 1, 5, 3, 0 };
System.out.println(oddballsum(numbers));
}
public static int oddballsum(int array[]) {
int sumodds = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 != 0) { sumodds = +(array[i]);}
}
return sumodds;
}
sumodds =+ (array[i]) means "assign the value of array[i] to sumodds". The + and the () make no difference - it's semantically identical to sumodds = array[i]. Use this if you just want the last odd value in the array.
sumodds += array[i] means "increase the value of sumodds by array[i]. Use this if you're trying to sum the odd values in the array.
The reason of the error is in this piece of code...
if (array[i] % 2 != 0) {
sumodds = +(array[i]);
}
you are not summing or accumulating you are just assigning the value with a positive sign
at the end, your code is just returning the last odd value found in the array...
you have to do instead something like:
if (array[i] % 2 != 0) {
sumodds += array[i];
}
If you write too much code, you have more chance to go wrong, you should use java 8 Streams:
int sumOdd = Arrays.stream(array).filter(t -> t%2==1).sum();
System.out.println(sumOdd);
The problem was with your addition operator =+. It should be += if you want to add and assign the new value to the same variable. Please refer below working code.
public static void main(String[] args) {
int[] numbers = {2, 1, 5, 3, 0};
System.out.println(oddballsum(numbers));
}
public static int oddballsum(int array[]) {
int sumodds = 0;
for(int element : array) {
if(element % 2 != 0) {
sumodds += element;
}
}
return sumodds;
}

What is the best way to check if ALL values in a range exist in an array? (java)

I have the task of determining whether each value from 1, 2, 3... n is in an unordered int array. I'm not sure if this is the most efficient way to go about this, but I created an int[] called range that just has all the numbers from 1-n in order at range[i] (range[0]=1, range[1]=2, ect). Then I tried to use the containsAll method to check if my array of given numbers contains all of the numbers in the range array. However, when I test this it returns false. What's wrong with my code, and what would be a more efficient way to solve this problem?
public static boolean hasRange(int [] givenNums, int[] range) {
boolean result = true;
int n = range.length;
for (int i = 1; i <= n; i++) {
if (Arrays.asList(givenNums).containsAll(Arrays.asList(range)) == false) {
result = false;
}
}
return result;
}
(I'm pretty sure I'm supposed to do this manually rather than using the containsAll method, so if anyone knows how to solve it that way it would be especially helpful!)
Here's where this method is implicated for anyone who is curious:
public static void checkMatrix(int[][] intMatrix) {
File numberFile = new File("valid3x3") ;
intMatrix= readMatrix(numberFile);
int nSquared = sideLength * sideLength;
int[] values = new int[nSquared];
int[] range = new int[nSquared];
int valCount = 0;
for (int i = 0; i<sideLength; i++) {
for (int j=0; j<sideLength; j++) {
values[valCount] = intMatrix[i][j];
valCount++;
}
}
for (int i=0; i<range.length; i++) {
range[i] = i+1;
}
Boolean valuesThere = hasRange(values, range);
valuesThere is false when printed.
First style:
if (condition == false) // Works, but at the end you have if (true == false) or such
if (!condition) // Better: not condition
// Do proper usage, if you have a parameter, do not read it in the method.
File numberFile = new File("valid3x3") ;
intMatrix = readMatrix(numberFile);
checkMatrix(intMatrix);
public static void checkMatrix(int[][] intMatrix) {
int nSquared = sideLength * sideLength;
int[] values = new int[nSquared];
Then the problem. It is laudable to see that a List or even better a Set approach is the exact abstraction level: going into detail not sensible. Here however just that is wanted.
To know whether every element in a range [1, ..., n] is present.
You could walk through the given numbers,
and for every number look whether it new in the range, mark it as no longer new,
and if n new numbers are reached: return true.
int newRangeNumbers = 0;
boolean[] foundRangeNumbers = new boolean[n]; // Automatically false
Think of better names.
You say you have a one dimensional array right?
Good. Then I think you are thinking to complicated.
I try to explain you another way to check if all numbers in an array are in number order.
For instance you have the array with following values:
int[] array = {9,4,6,7,8,1,2,3,5,8};
First of all you can order the Array simpel with
Arrays.sort(array);
After you've done this you can loop through the array and compare with the index like (in a method):
for(int i = array[0];i < array.length; i++){
if(array[i] != i) return false;
One way to solve this is to first sort the unsorted int array like you said then run a binary search to look for all values from 1...n. Sorry I'm not familiar with Java so I wrote in pseudocode. Instead of a linear search which takes O(N), binary search runs in O(logN) so is much quicker. But precondition is the array you are searching through must be sorted.
//pseudocode
int range[N] = {1...n};
cnt = 0;
while(i<-inputStream)
int unsortedArray[cnt]=i
cnt++;
sort(unsortedArray);
for(i from 0 to N-1)
{
bool res = binarySearch(unsortedArray, range[i]);
if(!res)
return false;
}
return true;
What I comprehended from your description is that the array is not necessarily sorted (in order). So, we can try using linear search method.
public static void main(String[] args){
boolean result = true;
int[] range <- Contains all the numbers
int[] givenNums <- Contains the numbers to check
for(int i=0; i<givenNums.length; i++){
if(!has(range, givenNums[i])){
result = false;
break;
}
}
System.out.println(result==false?"All elements do not exist":"All elements exist");
}
private static boolean has(int[] range, int n){
//we do linear search here
for(int i:range){
if(i == n)
return true;
}
return false;
}
This code displays whether all the elements in array givenNums exist in the array range.
Arrays.asList(givenNums).
This does not do what you think. It returns a List<int[]> with a single element, it does not box the values in givenNums to Integer and return a List<Integer>. This explains why your approach does not work.
Using Java 8 streams, assuming you don't want to permanently sort givens. Eliminate the copyOf() if you don't care:
int[] sorted = Arrays.copyOf(givens,givens.length);
Arrays.sort(sorted);
boolean result = Arrays.stream(range).allMatch(t -> Arrays.binarySearch(sorted, t) >= 0);
public static boolean hasRange(int [] givenNums, int[] range) {
Set result = new HashSet();
for (int givenNum : givenNums) {
result.add(givenNum);
}
for (int num : range) {
result.add(num);
}
return result.size() == givenNums.length;
}
The problem with your code is that the function hasRange takes two primitive int array and when you pass primitive int array to Arrays.asList it will return a List containing a single element of type int[]. In this containsAll will not check actual elements rather it will compare primitive array object references.
Solution is either you create an Integer[] and then use Arrays.asList or if that's not possible then convert the int[] to Integer[].
public static boolean hasRange(Integer[] givenNums, Integer[] range) {
return Arrays.asList(givenNums).containsAll(Arrays.asList(range));
}
Check here for sample code and output.
If you are using ApacheCommonsLang library you can directly convert int[] to Integer[].
Integer[] newRangeArray = ArrayUtils.toObject(range);
A mathematical approach: if you know the max value (or search the max value) check the sum. Because the sum for the numbers 1,2,3,...,n is always equal to n*(n+1)/2. So if the sum is equal to that expression all values are in your array and if not some values are missing. Example
public class NewClass12 {
static int [] arr = {1,5,2,3,4,7,9,8};
public static void main(String [] args){
System.out.println(containsAllValues(arr, highestValue(arr)));
}
public static boolean containsAllValues(int[] arr, int n){
int sum = 0;
for(int k = 0; k<arr.length;k++){
sum +=arr[k];
}
return (sum == n*(n+1)/2);
}
public static int highestValue(int[]arr){
int highest = arr[0];
for(int i = 0; i < arr.length; i++) {
if(highest<arr[i]) highest = arr[i];
}
return highest;
}
}
according to this your method could look like this
public static boolen hasRange (int [] arr){
int highest = arr[0];
int sum = 0;
for(int i = 0; i < arr.length; i++) {
if(highest<arr[i]) highest = arr[i];
}
for(int k = 0; k<arr.length;k++){
sum +=arr[k];
}
return (sum == highest *(highest +1)/2);
}

Find Max Number(s) in an ArrayList (Possibility of More Than One Max Value)

I would like to find the index/indices that hold the maximum value in an ArrayList. I want to preserve the order that the numbers are in (in other words no sorting) because I want to keep track of what index had what value. The values are from a random number generator and there is the possibility of having two (or more) indices sharing the same maximum value.
An example ArrayList:
12, 78, 45, 78
0,1,2,3 <- indices
(So indices, 1 and 3 contain the values that have the max values. I want to maintain the fact that indices 1 and 3 have the value 78. I do not want to just create a new ArrayList and have indices 0 and 1 of the new ArrayList have the values 78)
Therefore, I want to find all of the indices that have the maximum values because I will be doing something with them to "break" the tie if there is more than one index. So how can I find the indices that contain the maximum value and maintain the index-to-value relationship?
I have written the following methods:
public static ArrayList<Integer> maxIndices(ArrayList<Integer> numArrayList) {
// ???
return numArrayList;
}
public static void removeElement(ArrayList<Integer> numArrayList, int index) {
numArrayList.remove(index);
}
public static int getMaxValue(ArrayList<Integer> numArrayList) {
int maxValue = Collections.max(numArrayList);
return maxValue;
}
public static int getIndexOfMaxValue(ArrayList<Integer> numArrayList, int maxVal) {
int index = numArrayList.indexOf(maxVal);
return index;
}
public static ArrayList<Integer> maxIndices(ArrayList<Integer> list) {
List<Integer> indices = new ArrayList<Integer>();
int max = getMaxValue(list);
for (int i = 0; i < list.size(); i++) {
if(list.get(i) == max) {
indices.add(list.get(i));
}
}
return indices;
}
O(n) solution:
public static List<Integer> maxIndices(List<Integer> l) {
List<Integer> result = new ArrayList<Integer>();
Integer candidate = l.get(0);
result.add(0);
for (int i = 1; i < l.size(); i++) {
if (l.get(i).compareTo(candidate) > 0) {
candidate = l.get(i);
result.clear();
result.add(i);
} else if (l.get(i).compareTo(candidate) == 0) {
result.add(i);
}
}
return result;
}

Complexity and Efficiency in Algorithm for: a[j]-a[i] i>=j

I'm looking to make this much quicker. I've contemplated using a tree, but I'm not sure if that would actually help much.
I feel like the problem is for most cases you don't need to calculate all the possible maximums only a hand full, but I'm not sure where to draw the line
Thanks so much for the input,
Jasper
public class SpecialMax {
//initialized to the lowest possible value of j;
public static int jdex = 0;
//initialized to the highest possible value of i;
public static int idex;
//will hold possible maximums
public static Stack<Integer> possibleMaxs = new Stack<Integer> ();
public static int calculate (int[] a){
if (isPositive(a)){
int size = a.length;
int counterJ;
counterJ = size-1;
//find and return an ordered version of a
int [] ordered = orderBySize (a);
while (counterJ>0){
/* The first time this function is called, the Jvalue will be
* the largest it can be, similarly, the Ivalue that is found
* is the smallest
*/
int jVal = ordered[counterJ];
int iVal = test (a, jVal);
possibleMaxs.push(jVal-iVal);
counterJ--;
}
int answer = possibleMaxs.pop();
while (!possibleMaxs.empty()){
if (answer<possibleMaxs.peek()){
answer = possibleMaxs.pop();
} else {
possibleMaxs.pop();
}
}
System.out.println("The maximum of a[j]-a[i] with j>=i is: ");
return answer;
} else {
System.out.println ("Invalid input, array must be positive");
return 0; //error
}
}
//Check to make sure the array contains positive numbers
public static boolean isPositive(int[] a){
boolean positive = true;
int size = a.length;
for (int i=0; i<size; i++){
if (a[i]<0){
positive = false;
break;
}
}
return positive;
}
public static int[] orderBySize (int[] a){
//orders the array into ascending order
int [] answer = a.clone();
Arrays.sort(answer);
return answer;
}
/*Test returns an Ival to match the input Jval it accounts for
* the fact that jdex<idex.
*/
public static int test (int[] a, int jVal){
int size = a.length;
//initialized to highest possible value
int tempMin = jVal;
//keeps a running tally
Stack<Integer> mIndices = new Stack<Integer> ();
//finds the index of the jVal being tested
for (int i=0; i<size; i++) {
if (jVal==a[i]){
//finds the highest index for instance
if (jdex<i){
jdex = i;
}
}
}
//look for the optimal minimal below jdex;
for (int i=0; i<jdex; i++){
if (a[i]<tempMin){
tempMin = a[i];
mIndices.push(i);
}
}
//returns the index of the last min
if (!mIndices.empty()){
idex = mIndices.pop();
}
return tempMin;
}
}
It can be done in linear time and linear memory. The idea is: find the minimum over each suffix of the array and maximum over each prefix, then find the point where the difference between the two is the highest. You'll also have to store the index on which the maximum/minimum for each prefix is reached if you need the indices, rather than just the difference value.
Pre-sorting a[] makes the procedure complicated and impairs performance. It is not necessary, so we leave a[] unsorted.
Then (EDITED, because I had read j>=i in the body of your code, rather than i>=j in the problem description/title, which I now assume is what is required (I didn't go over your coding details); The two varieties can easily be derived from each other anyway.)
// initialize result(indices)
int iFound = 0;
int jFound = 0;
// initialize a candidate that MAY replace jFound
int jAlternative = -1; // -1 signals: no candidate currently available
// process the (remaining) elements of the array - skip #0: we've already handled that one at the initialization
for (int i=1; i<size; i++)
{
// if we have an alternative, see if that combines with the current element to a higher "max".
if ((jAlternative != -1) && (a[jAlternative]-a[i] > a[jFound]-a[iFound]))
{
jFound = jAlternative;
iFound = i;
jAlternative = -1;
}
else if (a[i] < a[iFound]) // then we can set a[iFound] lower, thereby increasing "max"
{
iFound = i;
}
else if (a[i] > a[jFound])
{ // we cannot directly replace jFound, because of the condition iFound>=jFound,
// but when we later may find a lower a[i], then it can jump in:
// set it as a waiting candidate (replacing an existing one if the new one is more promising).
if ((jAlternative = -1) || (a[i] > a[jAlternative]))
{
jAlternative = i;
}
}
}
double result = a[jFound] - a[iFound];

Categories

Resources