This is a perceptual question.
I want to know why there is an interference with these two independent methods.
I know both are reading the same array (my_array)
independently every response of the methods is correct. But when I turn on both of them (min and max methods), the response of the below method is wrong.
This is my code:
public class myPractice {
public static int max(int[] my_array1) {
int i = 0;
int max = my_array1[i];
for(i = 0; i < my_array1.length-1; i++) {
if(my_array1[i] > my_array1[i+1]) {
my_array1[i+1] = my_array1[i];
max = my_array1[i];
}else {
max = my_array1[i+1];
}
}
System.out.println("Max= " +max);
return max;
}
public static int min(int[] my_array2) {
int j = 0;
int min = my_array2[j];
for(j = 0; j < my_array2.length-1; j++) {
if(my_array2[j] < my_array2[j+1]) {
my_array2[j+1] = my_array2[j];
min = my_array2[j];
}else {
min = my_array2[j+1];
}
}
System.out.println("Min= " +min);
return min;
}
public static void main(String args[]) {
int[] my_array = {25, 14, 56, 5, 36, 89, 77, 18, 29, 49};
max(my_array);
min(my_array);
}
}
The issue is that you are altering the input array in the min and max methods:
my_array1[i+1] = my_array1[i];
As a result, in the next call, you are manipulating an array different from the initial one. As a matter of fact, in your script, max(my_array) sets my_array equals to [25, 25, 56, 56, 56, 89, 89, 89, 89, 89].
You can simplify min and max as the following ones:
public static int max(int[] myArr) {
int max = myArr[0];
for (int i = 1; i < myArr.length; i++){
if (myArr[i] > max)
max = myArr[i];
}
return max;
}
public static int min(int[] myArr) {
int min = myArr[0];
for (int i = 1; i < myArr.length; i++){
if (myArr[i] < min)
min = myArr[i];
}
return min;
}
Furthermore, I want to recommend some best practices:
use the camel case when programming in java. Write myArray instead of my_array;
print the result of a method in the main:
public static void main(String[] args) {
int[] myArray = {25, 14, 56, 5, 36, 89, 77, 18, 29, 49};
System.out.println("Max = " + max(myArray));
System.out.println("Min = " + min(myArray));
}
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I want to sort this array = {20, 46, 22, 19, 6, 42, 14, 5, 48, 47, 17, 39, 51, 7, 2} using bucket sort. I get a arrayindexoutofboundsexception error in my code. Can someone please help me to correct my code...
package com.bucketsort;
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] arr = {20, 46, 22, 19, 6, 42, 14, 5, 48, 47, 17, 39, 51, 7, 2};
System.out.println("Unsorted: " + Arrays.toString(arr));
bucketSort(arr);
System.out.println("Sorted : " + Arrays.toString(arr));
}
public static int[] bucketSort(int[] arr) {
int max = getMax(arr);
int[] sortedArray = new int[max + 1];
//loop and place n at nth position
for (int cur : arr) {
for (int i = 0; i <= max; i++) {
int currentVal = arr[i];
sortedArray[currentVal] = currentVal;
}
}
return sortedArray;
}
//method to get the maximum value
public static int getMax(int[] arr) {
int maxValue = arr[0];
for(int i=1;i<arr.length;i++) {
if(arr[i] > maxValue) {
maxValue = arr[i];
}
}
return maxValue;
}
}
This is a screenshot of what I get when i run this code.
The problem starts here:
for (int i = 0; i <= max; i++) {
int currentVal = arr[i];
sortedArray[currentVal] = currentVal;
}
Since you are returning the value from the getMax function instead of index.
The problem here is this part of your code, you loop from the 0 to max for the arr which its length fixed 15 and before the max
for (int cur : arr) {
for (int i = 0; i <= max; i++) { <---
int currentVal = arr[i]; <---
sortedArray[currentVal] = currentVal;
}
}
, Just remove that and use the following:
for (int cur : arr) {
sortedArray[curr] = curr;
}
This question already has answers here:
Creating a random array of type int. Java
(3 answers)
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 1 year ago.
I am just looking to change my code so that a random array of a fixed length of 100 integers is generated every time the code is ran rather than just have a pre-set array within the code. I am quite new to this so just need a guide in the right direction, thanks
public class Selectionsort {
public static void main(String[] args) {
int[] numbers = {15, 8, 6, 21, 3, 54, 6, 876, 56, 12, 1, 4, 9};
sort(numbers);
printArray(numbers);
}
public static int[] sort(int[] A) {
for (int i = 0; i < A.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < A.length; j++) {
if (A[j] < A[minIndex]) {
minIndex = j;
}
}
int temp = A[minIndex];
A[minIndex] = A[i];
A[i] = temp;
}
return A;
}
public static void printArray(int[] A) {
for (int i = 0; i < A.length; i++) {
System.out.println(A[i]);
}
}
}
public class Selectionsort {
public static void main(String[] args) {
int[] numbers = new int[100]
Random random = new Random();
for (int i = 0; i < numbers.length; i++) {
numbers[i] = random.nextInt(100);
}
sort(numbers);
printArray(numbers);
}
}
The above snippet will help you to create a random numbers between 1 to 100 for the array of size 100.
You should look at the Random class.
More specifically:
nextInt() to fill it one by one
ints(long) to get an IntStream of fixed size, which can be easily converted to an array with .toArray()
The below would fill an array of 100 integers with Random numbers from 1-1000
int[] numbers = new int[100];
Random rand = new Random();
for (int i = 0; i < numbers.length; i++) {
numbers[i] = rand.nextInt(1000);
}
However note that the above code might insert duplicates. If you want to avoid that, using a List in parallel to the array and checking whether the generated value already exists should ensure uniqueness :
int[] numbers = new int[100];
List<Integer> numbersList = new ArrayList<Integer>(numbers.length);
Random rand = new Random();
for (int i = 0; i < numbers.length; i++) {
int j = rand.nextInt(1000);
while (numbersList.contains(j)) {
j = rand.nextInt(1000);
}
numbers[i] = j;
numbersList.add(j);
}
Even though I think it would be wiser to get rid of the array and use just the List...
You can use Math.random method. This code generates an array of 10 random numbers in the range [50,60] inclusive.
int length = 10, min = 50, max = 60;
int[] arr = IntStream.range(0, length)
.map(i -> (int) (min + Math.random() * (max - min + 1)))
.toArray();
System.out.println(Arrays.toString(arr));
// [54, 51, 58, 59, 57, 56, 56, 54, 54, 58]
Full set of 11 random numbers:
Set<Integer> set = new HashSet<>();
while (set.size() < max - min + 1) {
set.add((int) (min + Math.random() * (max - min + 1)));
}
System.out.println(set);
// [50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60]
Lifts are usually limited in capacity, both in space (persons) as in load (kgs). Imagine we have
a small lift which is capable of transporting a maximum of 6 persons and a maximum load of
500kg. Suppose 13 people are waiting with the following weights: 10, 30, 40, 41, 80, 90, 50, 55,
92, 66, 82, 62 and 70kg. Write a recursive program that finds a group of people that does not
exceed the maximum capacities, but has the maximum possible load in kg. (Hint: there is a valid
solution that exceeds 470kg)
public static void main (String[] Args)
{
ArrayList<Integer> s = new ArrayList<Integer>(); //List of unexplored
int[] weight0 = { 10, 30, 40, 41, 80, 90, 50, 55, 92, 66, 82, 62,70}; //Initial state
int target = 500; //Goal state
System.out.println(liftGroup(weight0,0,target, s) + " way(s)"); //Recursive function
}
static int liftGroup (int[] weight,int c,int target, ArrayList<Integer> s){
assert weight != null : "array should be initialized";
assert c >= 0 && c <= weight.length;
assert s != null : "ArrayList should be initialized";
int sumOfUntried = 0;
if (c > 6) {
showSoulution(s);
return 1;
}
else if (target < 0) {
return 0;
}
else if (c >= weight.length) { //that's okay?
return 0;
}
int min = weight[c];
for (int i = c; i < weight.length; i++) {
sumOfUntried += weight[i];
if(weight[i]<min)
min=weight[i];
}
if(min>target) // If you find one BIG fatty
{
return 0;
}
if (sumOfUntried > target) { //Correct
return 0;
}
else {
s.add(weight[c]);
int with = liftGroup(weight, c + 1, target - weight[c], s);
s.remove(s.size() - 1);
int without = liftGroup(weight, c + 1, target, s);
return with + without;
}
}
/*
* Prints the ArrayList with the solution
*/
private static void showSoulution(ArrayList<Integer> s)
{
assert s != null : "ArrayList should be initialized";
System.out.println("Solution: " + s);
}}
My problem is understanding and using the base case:
When the number of persons does not exceed the maximum limits. You've got a solution.
But how do I comply with the two goals?
Here's a little bit of a messy solution*, which I threw together with credit from here, here and here.
Basically, for each iteration, add the combination, and its sum to a HashMap.
Then sort the HashMap by value.
Finally, loop through HashMap and find closest value to your target.
static Map<String, Integer> myMap = new HashMap<>();
static void combinationUtil(int arr[], int data[], int start,
int end, int index, int r) {
int sum = 0;
StringBuilder sb = new StringBuilder();
if (index == r) {
for (int j = 0; j < r; j++) {
sb.append(data[j]).append(",");
sum += data[j];
System.out.print(data[j] + " ");
}
myMap.put(sb.toString(), sum);
sum = 0;
sb = new StringBuilder();
System.out.println("");
return;
}
for (int i = start; i <= end && end - i + 1 >= r - index; i++) {
data[index] = arr[i];
combinationUtil(arr, data, i + 1, end, index + 1, r);
}
}
static void printCombination(int arr[], int n, int r) {
int data[] = new int[r];
combinationUtil(arr, data, 0, n - 1, 0, r);
}
public static void main(String[] args) {
int arr[] = {10, 30, 40, 41, 80, 90, 50, 55, 92, 66, 82, 62, 70};
int r = 6; //as you have 6 people
int n = arr.length;
printCombination(arr, n, r);
myMap = sortByValue(myMap);
System.out.println(searchClosest(myMap, 500)); //500 is the target
}
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
return map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(/*Collections.reverseOrder()*/))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new
));
}
public static String searchClosest(Map<String, Integer> map, int value) {
double minDistance = Double.MAX_VALUE;
String bestString = null;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
double distance = Math.abs(entry.getValue() - value);
if (distance < minDistance) {
minDistance = distance;
bestString = entry.getKey();
}
}
return bestString;
}
Here's an online example with int arr[] = {1,2,3,4,5,6,7,8}; and the permutations set to 3, and target of 14.
*This is just copied/pasted with one or two minor modifications but is more just an idea of how to get your solution
I have a given array with the temperatures of days and I need to build a class that finds out how many days have had the temperature 22°C. Here is what I did:
public class Frequence {
public static void main(String args[]){
int arr[] = {20,22,18,19,20,25,27,30,29,29,24,22,16,18,20,23,21,22,26,30,28,29,28,27,26,26,27,23,24,25};
System.out.println(count);
}
public static int frekuenc(int[] arr) {
int count=0;
int i=0;
while(i<arr.length) {
if(arr[i]==22) {
count=count+1;
i++;
return count;
}
}
}
}
I'm guessing your code loops infinitely, because i++ is inside the if. Move it to the end of the loop instead. And the return statement should be moved out of the loop altogether. Otherwise it'll return on the first match.
int count = 0;
int i = 0;
while(i<arr.length) {
if(arr[i]==22){
count++;
}
i++;
}
return count;
Or you could use a more conventional for loop:
int count = 0;
for (int i = 0; i < arr.length; i++) {
if(arr[i]==22){
count++;
}
}
return count;
Or an enhanced for:
int count = 0;
for (int n : arr) {
if (n == 2) {
count++;
}
}
return count;
Or a stream:
return Arrays.stream(arr)
.filter(n -> n == 22)
.count();
public class Frequence {
public static void main(String args[]) {
int arr[] = { 20, 22, 18, 19, 20, 25, 27, 30, 29, 29, 24, 22, 16, 18, 20, 23, 21, 22, 26, 30, 28, 29, 28, 27,
26, 26, 27, 23, 24, 25 };
System.out.println(frekuenc(arr, 22));
}
public static int frekuenc(int[] arr, int tempToFind) {
HashMap<Integer, Integer> countMap = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
Integer temperature = new Integer(arr[i]);
if (countMap.get(temperature) != null) {
countMap.put(temperature, countMap.get(temperature) + 1);
} else {
countMap.put(temperature, 1);
}
}
return countMap.get(tempToFind);
}
}
How can I make this code not have any repeating numbers in it?
All I would like to do is make it so that it doesn't output any duplicates
in this little block.
int[] arr = {5,10,44,2, 44,44,5,10,44,2, 44,44};
int startScan;
int index;
int minindex;
int minValue;
for (startScan=0;startScan<(arr.length-1);startScan++){
minindex=startScan;
minValue =arr[startScan];
for (index=startScan+1; index<arr.length;index++){
if (arr[index]<minValue){
minValue=arr[index];
minindex=index;
}
}
arr[minindex]=arr[startScan];
arr[startScan]=minValue;
}
for(int x=0; x<arr.length;x++)
System.out.println(arr[x]);
Your code sorted the int array in ascending order. It would have been nice if you had mentioned that in your question, and not left it for someone else to spend time figuring out.
Removing the duplicates required some extra code.
Here is the results of a test run.
[2, 5, 10, 44]
Here's the revised version of your code. It's runnable, so you can copy the code and paste it into your IDE.
package com.ggl.testing;
import java.util.Arrays;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] arr = { 5, 10, 44, 2, 44, 44, 5, 10, 44, 2, 44, 44 };
int masterIndex = 0;
for (int startScan = 0; startScan < (arr.length - 1); startScan++) {
int minindex = startScan;
int minValue = arr[startScan];
for (int index = startScan + 1; index < arr.length; index++) {
if (arr[index] < minValue) {
minValue = arr[index];
minindex = index;
}
}
arr[minindex] = arr[startScan];
arr[startScan] = minValue;
if (arr[masterIndex] < minValue) {
arr[++masterIndex] = minValue;
}
}
int[] newarr = Arrays.copyOf(arr, masterIndex + 1);
System.out.println(Arrays.toString(newarr));
}
}