So this is my first post and I'm fairly new to coding. I am populating an array with 5 random integers. I then want to iterate through that array and find any duplicates, storing the duplicate integers that occurs most often in a new array. So essentially if the random generate integers were say, [6,2,2,1,1] i would expect that the second method should loop and create a new array with two integers both with a value of 2 or [2,2].
private int min = 1;
private int max = 6;
private int[] randArray = new int[5];
private int num1;
private int num2;
private int num3;
private int num4;
private int num5;
private int num6;
private int[] maxFreqArray = new int[6];
public int[] fillRandArray() {
for (int i = 0; i < randArray.length; i++) {
randArray[i] = random.nextInt(max) + min;
}
return randArray;
}
public int[] fillMaxFreqArray() {
for (int i = 1; i < maxFreqArray.length; i++) {
if (randArray[i] == 1) {
maxFreqArray[i] = num1++;
} else if (randArray[i] == 2) {
maxFreqArray[i] = num2++;
} else if (randArray[i] == 3) {
maxFreqArray[i] = num3++;
} else if (randArray[i] == 4) {
maxFreqArray[i] = num4++;
} else if (randArray[i] == 5) {
maxFreqArray[i] = num5++;
} else if (randArray[i] == 6) {
maxFreqArray[i] = num6++;
}
}
return maxFreqArray;
}
My problem is two fold, first it appears I am populating the maxFreqArray with only 5 integers as when I print the array I get random value of [0, 2, 1, 1, 3] or something similar but never anything greater than 3. Any ideas?
Here you go,
public static void main(String[] args) {
int[] a = { 6, 2, 2, 1, 1 ,1 };
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < a.length; i++) {
if (map.get(a[i]) != null) {
map.put(a[i], map.get(a[i]) + 1);
} else {
map.put(a[i], 1);
}
}
int maxvalue = 0, respectiveKey = 0;
for (Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() >= maxvalue) {
maxvalue = entry.getValue();
respectiveKey = entry.getKey();
}
}
int[] newarra = new int[maxvalue];
for (int i = 0; i < maxvalue; i++) {
newarra[i] = respectiveKey;
}
// return newarra;
}
This is solution is in java 5, If you are familiar with java 7 and 8 onwards you can use stream operation to achieve the same.
hope this will help you.
I don't have the time to write out the Java, but the algorithm I would use is as follows, assuming random numbers are integers >= 0:
resArr = new array<int>(<max of range + 1>)
// i.e. if random numbers are in 1-6, max of range is 7
// array is initialized to default values (0)
// [0,0,0,0,0,0,0]
for i in randomNumberArray // [6,2,2,1,1]
resArr[randomNumberArray[i]]++
// use value of random number to index into res array and increment count
// now have a res array that looks like [0,2,2,0,0,0,1]
maxCount = 0
maxIndex = 0
for i in resArr
if resArr[i] >= maxCount
maxIndex = i
// each time resArr has a count >= equal to
// the current max count, grab that index
// since we want the highest matching duplicate
return maxIndex
// maxIndex is the value from the random array
// i.e. 2 for this example
This uses a temp array to hold the counts of numbers seen in the random array, the index being the value from the random array. One O(n) pass over the random number array, and one O(range) pass over the result array to compute the max count seen.
To get random numbers in range [min, max] inclusive:
int random(int min, int max) {
return random.nextInt((max - min) + 1) + min;
}
So, in fillRandArray you can use randArray[i] = random(min, max);
Also, you actually declare private int[] randArray = new int[5];. So, that's why you always get randArray of size 5.
The formula above should be applied because random.nextInt(bound) returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified bound (exclusive). So:
Minimum value returned by random.nextInt(bound) is 0. By using either random.nextInt(max) + min or random.nextInt((max - min) + 1) + min you'll get min value as result.
Maximum value returned by random.nextInt(bound) is bound - 1. By using formula random.nextInt(max) you'll actually get max possible value max - 1 + min. Because of this, you should use random.nextInt((max - min) + 1), so at bound case you'll get (max - min) + min, which is equal to max.
I've searched through a several similar threads with the exact problem, however I have been unable to get the code to work, I want to find the closest value in the array and then remove it, here is my code :
import java.util.ArrayList;
import java.util.Scanner;
public class Entertrain {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Power: ");
int power = Integer.parseInt(console.nextLine());
ArrayList<Integer> weight = new ArrayList<>();
int averageWagon = 0;
int sum = 0;
while (console.hasNextInt()) {
weight.add(console.nextInt());
}
for (int i = 0; i < weight.size(); i++)
sum += weight.get(i);
if (sum > power) {
averageWagon = sum / weight.size();
//Here I want to find the closest value to averageWagon
}
System.out.println(averageWagon);
System.out.println(weight);
System.out.println(power);
System.out.println(sum);
}
}
If it would be possible to guide me to a solution, I've tried for a few hours now and I've ended with the conclusion that I seriously lack knowledge of arrays, so in any case I will put aside this and focus on arrays for now, but would be grateful for help on this one.
It is not arrays you are looking for, it is Collections. You are using ArrayList, which implements the List.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Power: ");
int power = Integer.parseInt(console.nextLine());
ArrayList<Integer> weight = new ArrayList<>();
int averageWagon = 0;
int sum = 0;
while (console.hasNextInt()) {
weight.add(console.nextInt());
}
for (int i = 0; i < weight.size(); i++)
sum += weight.get(i);
if (sum > power) {
averageWagon = sum / weight.size();
Integer closest = weight.get(0);
for (Integer i: weight) {
if (Math.abs(averageWagon - closest) > Math.abs(averageWagon - i))
closest = i;
}
weight.remove(closest);
}
System.out.println(averageWagon);
System.out.println(weight);
System.out.println(power);
System.out.println(sum);
}
You can do something like this
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Power: ");
int power = Integer.parseInt(console.nextLine());
ArrayList<Integer> weight = new ArrayList<>();
int averageWagon = 0;
int sum = 0;
while (console.hasNextInt()) {
weight.add(console.nextInt());
}
for (int i = 0; i < weight.size(); i++) {
sum += weight.get(i);
}
if (sum > power) {
averageWagon = sum / weight.size();
//Here I want to find the closest value to averageWagon
int closest = findClosestNumber(averageWagon, weight);
System.out.println("Closest number to average: "+ closest);
}
System.out.println(averageWagon);
System.out.println(weight);
System.out.println(power);
System.out.println(sum);
}
static int findClosestNumber(int num, List<Integer> numbers) {
int closest = numbers.get(0);
for (int i : numbers) {
if (Math.abs(num - i) < Math.abs(num - closest)) {
closest = i;
}
}
return closest;
}
Here's a way to do it with streams:
int sum = weight.stream().mapToInt(Integer::intValue).sum();
if (sum > power) {
int avg = sum / weight.size(); // shouldn't it be double?
weight.stream()
.min((a, b) -> Integer.compare(Math.abs(a - avg), Math.abs(b - avg)))
.ifPresent(weight::remove); // remove closest number from weight
} // list if found (i.e. if list not empty)
First a stream is used to find the sum, then the average is calculated and finally, Stream.min is used to find the minimum element of the stream, which is the one that is closest to the average.
Stream.min receives a Comparator as an argument, which has the usual comparator semantics: if the first argument is less than the second one, return a negative value; if greater, return a positive value, otherwise (if equal), return zero. In this case, a is less than b if its distance to the average is less than b's distance to the average. Here I'm using Integer.compare to perform the comparison.
Note that Stream.min doesn't return the minimum number, but an Optional<Integer> instead. This is because the weight list might be empty, so in this case there would be no minimum element. This is when the Optional.ifPresent method comes in handy: if a minimum has been found, then we remove it from the weight list, otherwise nothing happens.
I am working on a school assignment and I have the following question:
I am given a number of sticks (with distinct or similar length), and am tasked to find out the minimum number of sticks required to form a longer stick of given length.
For instance,
Given 6 sticks of length 1,1,1,1,1,3 to form a longer stick of length 5, the output would be 3.
NOTE: Sticks cannot be reused.
However, if it is impossible to form the given length, output -1.
For instance,
Given 3 sticks of length 1,2,6, to form a longer stick of length 5, output would be -1.
I have the following code, which have passed all public test cases. However, I failed the private test cases which I cannot figure out my mistake.
Here's my code:
import java.util.*;
class Result {
static int min = 100000;
public static int solve(int pos, int currSum, int len, int numStk) {
// implementation
for (int i=1; i<=Stick.data.length - pos; i++){
if (currSum > len){
continue;
}
else if (currSum < len){
if (pos+i >= Stick.data.length){
break;
}
else{
solve(pos+i,currSum+Stick.data[pos+i], len, numStk+1);
}
}
else if (currSum == len){
if (numStk < min){
min = numStk;
}
}
}
return min;
}
}
class Stick {
static int[] data;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sticks = sc.nextInt();
data = new int[sticks];
int len = sc.nextInt();
for (int i=0; i<sticks; i++){
data[i] = sc.nextInt();
}
for (int i=0; i<sticks; i++){
Result.solve(i,0,len,1);
}
if (Result.min == 100000){
System.out.println(-1);
} else {
System.out.println(Result.min-1);
}
}
}
Things I notice about your code:
Bug: In main,
Result.solve(i,0,len,1);
assumes that stick i is taken (hence numsticks = 1 in the arguments list), but currSum is given as 0. Shouldn't that be data[i]?
Better code quality: The checks for currSum > len and currSum == len can be done outside the for loop, which is more efficient.
I'm having a problem finding the sum of all of the integers in an array in Java. I cannot find any useful method in the Math class for this.
In java-8 you can use streams:
int[] a = {10,20,30,40,50};
int sum = IntStream.of(a).sum();
System.out.println("The sum is " + sum);
Output:
The sum is 150.
It's in the package java.util.stream
import java.util.stream.*;
If you're using Java 8, the Arrays class provides a stream(int[] array) method which returns a sequential IntStream with the specified int array. It has also been overloaded for double and long arrays.
int [] arr = {1,2,3,4};
int sum = Arrays.stream(arr).sum(); //prints 10
It also provides a method
stream(int[] array, int startInclusive, int endExclusive) which permits you to take a specified range of the array (which can be useful) :
int sum = Arrays.stream(new int []{1,2,3,4}, 0, 2).sum(); //prints 3
Finally, it can take an array of type T. So you can per example have a String which contains numbers as an input and if you want to sum them just do :
int sum = Arrays.stream("1 2 3 4".split("\\s+")).mapToInt(Integer::parseInt).sum();
This is one of those simple things that doesn't (AFAIK) exist in the standard Java API. It's easy enough to write your own.
Other answers are perfectly fine, but here's one with some for-each syntactic sugar.
int someArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;
for (int i : someArray)
sum += i;
Also, an example of array summation is even shown in the Java 7 Language Specification. The example is from Section 10.4 - Array Access.
class Gauss {
public static void main(String[] args) {
int[] ia = new int[101];
for (int i = 0; i < ia.length; i++) ia[i] = i;
int sum = 0;
for (int e : ia) sum += e;
System.out.println(sum);
}
}
You can't. Other languages have some methods for this like array_sum() in PHP, but Java doesn't.
Just..
int[] numbers = {1,2,3,4};
int sum = 0;
for( int i : numbers) {
sum += i;
}
System.out.println(sum);
In Apache Math : There is StatUtils.sum(double[] arr)
The only point I would add to previous solutions is that I would use a long to accumulate the total to avoid any overflow of value.
int[] someArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, Integer.MAX_VALUE};
long sum = 0;
for (int i : someArray)
sum += i;
int sum = 0;
for (int i = 0; i < yourArray.length; i++)
{
sum = sum + yourArray[i];
}
In Java 8
Code:
int[] array = new int[]{1,2,3,4,5};
int sum = IntStream.of(array).reduce( 0,(a, b) -> a + b);
System.out.println("The summation of array is " + sum);
System.out.println("Another way to find summation :" + IntStream.of(array).sum());
Output:
The summation of array is 15
Another way to find summation :15
Explanation:
In Java 8, you can use reduction concept to do your addition.
Read all about Reduction
A bit surprised to see None of the above answers considers it can be multiple times faster using a thread pool. Here, parallel uses a fork-join thread pool and automatically break the stream in multiple parts and run them parallel and then merge. If you just remember the following line of code you can use it many places.
So the award for the fastest short and sweet code goes to -
int[] nums = {1,2,3};
int sum = Arrays.stream(nums).parallel().reduce(0, (a,b)-> a+b);
Lets say you want to do sum of squares , then Arrays.stream(nums).parallel().map(x->x*x).reduce(0, (a,b)-> a+b). Idea is you can still perform reduce , without map .
int sum = 0;
for (int i = 0; i < myArray.length; i++)
sum += myArray[i];
}
IMHO a sum function would seem a good fit to extend the Arrays class where fill, sort, search, copy, & equals live. There are a lot of handy methods hiding in the javadocs so it is a fair question when porting Fortran to java to ask before rolling our own helper method. Search through the huge javadoc index for "sum", "add" and any other keyword you might think of. You might suspect certainly someone has already done this for primitive types int, float, double, Integer, Float, Double? No matter how simple, it is always good to check. Keep the code as simple as possible and don't reinvent the wheel.
It depends. How many numbers are you adding? Testing many of the above suggestions:
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Locale;
public class Main {
public static final NumberFormat FORMAT = NumberFormat.getInstance(Locale.US);
public static long sumParallel(int[] array) {
final long start = System.nanoTime();
int sum = Arrays.stream(array).parallel().reduce(0,(a,b)-> a + b);
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumStream(int[] array) {
final long start = System.nanoTime();
int sum = Arrays.stream(array).reduce(0,(a,b)-> a + b);
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumLoop(int[] array) {
final long start = System.nanoTime();
int sum = 0;
for (int v: array) {
sum += v;
}
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumArray(int[] array) {
final long start = System.nanoTime();
int sum = Arrays.stream(array) .sum();
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumStat(int[] array) {
final long start = System.nanoTime();
int sum = 0;
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static void test(int[] nums) {
System.out.println("------");
System.out.println(FORMAT.format(nums.length) + " numbers");
long p = sumParallel(nums);
System.out.println("parallel " + FORMAT.format(p));
long s = sumStream(nums);
System.out.println("stream " + FORMAT.format(s));
long ar = sumArray(nums);
System.out.println("arrays " + FORMAT.format(ar));
long lp = sumLoop(nums);
System.out.println("loop " + FORMAT.format(lp));
}
public static void testNumbers(int howmany) {
int[] nums = new int[howmany];
for (int i =0; i < nums.length;i++) {
nums[i] = (i + 1)%100;
}
test(nums);
}
public static void main(String[] args) {
testNumbers(3);
testNumbers(300);
testNumbers(3000);
testNumbers(30000);
testNumbers(300000);
testNumbers(3000000);
testNumbers(30000000);
testNumbers(300000000);
}
}
I found, using an 8 core, 16 G Ubuntu18 machine, the loop was fastest for smaller values and the parallel for larger. But of course it would depend on the hardware you're running:
------
3 numbers
6
parallel 4,575,234
6
stream 209,849
6
arrays 251,173
6
loop 576
------
300 numbers
14850
parallel 671,428
14850
stream 73,469
14850
arrays 71,207
14850
loop 4,958
------
3,000 numbers
148500
parallel 393,112
148500
stream 306,240
148500
arrays 335,795
148500
loop 47,804
------
30,000 numbers
1485000
parallel 794,223
1485000
stream 1,046,927
1485000
arrays 366,400
1485000
loop 459,456
------
300,000 numbers
14850000
parallel 4,715,590
14850000
stream 1,369,509
14850000
arrays 1,296,287
14850000
loop 1,327,592
------
3,000,000 numbers
148500000
parallel 3,996,803
148500000
stream 13,426,933
148500000
arrays 13,228,364
148500000
loop 1,137,424
------
30,000,000 numbers
1485000000
parallel 32,894,414
1485000000
stream 131,924,691
1485000000
arrays 131,689,921
1485000000
loop 9,607,527
------
300,000,000 numbers
1965098112
parallel 338,552,816
1965098112
stream 1,318,649,742
1965098112
arrays 1,308,043,340
1965098112
loop 98,986,436
I like this method personally. My code style is a little weird.
public static int sumOf(int... integers) {
int total = 0;
for (int i = 0; i < integers.length; total += integers[i++]);
return total;
}
Pretty easy to use in code:
int[] numbers = { 1, 2, 3, 4, 5 };
sumOf(1);
sumOf(1, 2, 3);
sumOf(numbers);
I use this:
public static long sum(int[] i_arr)
{
long sum;
int i;
for(sum= 0, i= i_arr.length - 1; 0 <= i; sum+= i_arr[i--]);
return sum;
}
You have to roll your own.
You start with a total of 0. Then you consider for every integer in the array, add it to a total. Then when you're out of integers, you have the sum.
If there were no integers, then the total is 0.
There are two things to learn from this exercise :
You need to iterate through the elements of the array somehow - you can do this with a for loop or a while loop.
You need to store the result of the summation in an accumulator. For this, you need to create a variable.
int accumulator = 0;
for(int i = 0; i < myArray.length; i++) {
accumulator += myArray[i];
}
You can make your code look better like this:
public void someMethod(){
List<Integer> numbers = new ArrayList<Integer>();
numbers.addAll(db.findNumbers());
...
System.out.println("Result is " + sumOfNumbers(numbers));
}
private int sumOfNumbers(List<Integer> numbers){
int sum = 0;
for (Integer i : numbers){
sum += i;
}
return sum;
}
Use below logic:
static int sum()
{
int sum = 0; // initialize sum
int i;
// Iterate through all elements summing them up
for (i = 0; i < arr.length; i++)
sum += arr[i];
return sum;
}
I have the right solution for your problem if you specifically have an array of type double, then this method can be used to calculate the sum of its elements. also, it using math class
import org.apache.commons.math3.stat.StatUtils;
public class ArraySum {
public static void main(String[] args) {
double[] array = { 10, 4, 17, 33, -2, 14 };
int sum = (int)StatUtils.sum(array);
System.out.println("Sum of array elements is: " + sum);
}
}
There is a sum() method in underscore-java library.
Code example:
import com.github.underscore.U;
public class Main {
public static void main(String[] args) {
int sum = U.sum(java.util.Arrays.asList(1, 2, 3, 4));
System.out.println(sum);
// -> 10
}
}
There is no 'method in a math class' for such thing. Its not like its a square root function or something like that.
You just need to have a variable for the sum and loop through the array adding each value you find to the sum.
class Addition {
public static void main() {
int arr[]={5,10,15,20,25,30}; //Declaration and Initialization of an Array
int sum=0; //To find the sum of array elements
for(int i:arr) {
sum += i;
}
System.out.println("The sum is :"+sum);//To display the sum
}
}
We may use user defined function. At first initialize sum variable equal to zero. Then traverse the array and add element with sum . Then update the sum variable.
Code Snippet :
import java.util.*;
import java.lang.*;
import java.io.*;
class Sum
{
public static int sum(int arr[])
{
int sum=0;
for(int i=0; i<arr.length; i++)
{
sum += arr[i];
}
return sum;
}
public static void main (String[] args)
{
int arr[] = {1, 2, 3, 4, 5};
int total = sum(arr);
System.out.printf("%d", total);
}
}
/**
* Sum of all elements from 1 to 1000
*/
final int sum = Stream.iterate(1, n -> n + 1).limit(1000).mapToInt(el -> el).sum();
Most of the answers here are using inbuilt functions-
Here is my answer if you want to know the whole logic behind this ques:
import java.util.*;
public class SumOfArray {
public static void main(String[] args){
Scanner inp = new Scanner(System.in);
int n = inp.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i] = inp.nextInt();
}
System.out.println("The sum of the array is :" + sum(arr));
}
static int sum(int[] arr){
int sum = 0;
for (int a = 0; a < arr.length; a++){
sum = sum + arr[a];
}
return sum;
}
}
public class Num1
{
public static void main ()
{
//Declaration and Initialization
int a[]={10,20,30,40,50}
//To find the sum of array elements
int sum=0;
for(int i=0;i<a.length;i++)
{
sum=sum+i;
}
//To display the sum
System.out.println("The sum is :"+sum);
}
}
public class AddDemo {
public static void main(String[] args) {
ArrayList <Integer>A = new ArrayList<Integer>();
Scanner S = new Scanner(System.in);
System.out.println("Enter the Numbers: ");
for(int i=0; i<5; i++){
A.add(S.nextInt());
}
System.out.println("You have entered: "+A);
int Sum = 0;
for(int i=0; i<A.size(); i++){
Sum = Sum + A.get(i);
}
System.out.println("The Sum of Entered List is: "+Sum);
}
}
As of Java 8 The use of lambda expressions have become available.
See this:
int[] nums = /** Your Array **/;
Compact:
int sum = 0;
Arrays.asList(nums).stream().forEach(each -> {
sum += each;
});
Prefer:
int sum = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
for (int each : nums) { //refer back to original array
list.add(each); //there are faster operations…
}
list.stream().forEach(each -> {
sum += each;
});
Return or print sum.