Summing Numbers in an Array Greater than an Inputted Value - java

Need to add all numbers in an array that is greater than an inputted number. The seed is just so the output can be replicated.
Example:
[12,16,45,3,32]
Inputted Value: 30
Output:
77
import java.util.*;
public class SumAbove {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int seed = scnr.nextInt();
Random rand = new Random(seed);
System.out.println("Enter a positive integer between 1-100 to search above:");
int minVal = scnr.nextInt();
int[] arr = new int[rand.nextInt(100)+1];
for (int i=0; i<arr.length; i++) {
arr[i] = rand.nextInt(100)+1;
}
System.out.println(Arrays.toString(arr));
int sum = 0;
for (int i=0; i<arr.length; i++) {
if (arr[i]>minVal) {
sum += i;
}
}
System.out.println(sum);
}
}

Instead of sum += i; you want sum += arr[i]; (as already noted), you also only need one loop (since you know the minimum before the first loop). Like,
int minVal = scnr.nextInt(), sum = 0;
int[] arr = new int[rand.nextInt(100) + 1];
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt(100) + 1;
if (arr[i] > minVal) {
sum += arr[i];
}
}
System.out.println(Arrays.toString(arr));
System.out.println(sum);

Replace sum += i with sum += arr[i].
The variable i is just the position. arr[i] is the value at that position.

public static void main(String[] args) {
int nums[] = { 12, 16, 45, 3, 32 };
int value;
int sum = 0;
System.out.println("Enter a positive integer between 1-100 to search above: ");
Scanner sc = new Scanner(System.in);
value = sc.nextInt();
for (int i = 0; i < nums.length; i++) {
if (nums[i] > value)
sum = nums[i] + sum;
}
System.out.println(sum);
}

Here is how you can do it with streams in Java 8+.
int nValues = 5;
int minValue = 1;
int maxValue = 30;
Random r = new Random();
for (int i = 0; i < 10; i++) {
int[] values = r.ints(nValues, minValue, maxValue + 1).toArray();
// min to sum is the threshold
int minToSum = r.nextInt(7) + 10; // between 10 an 16 inclusive
int sum = Arrays.stream(values).filter(m -> m > minToSum).sum();
System.out.println("sum = " + sum + " for greater than " + minToSum
+ " : " + Arrays.toString(values));
}
The following output.
sum = 65 for values greater than 11 : [2, 10, 14, 23, 28]
sum = 92 for values greater than 10 : [13, 18, 15, 19, 27]
sum = 94 for values greater than 12 : [25, 6, 14, 25, 30]
sum = 54 for values greater than 10 : [14, 8, 14, 26, 5]
sum = 22 for values greater than 15 : [15, 8, 13, 22, 14]
sum = 28 for values greater than 13 : [3, 28, 9, 6, 5]
sum = 87 for values greater than 13 : [5, 18, 25, 21, 23]
sum = 31 for values greater than 13 : [16, 7, 12, 2, 15]
sum = 42 for values greater than 15 : [7, 22, 20, 10, 5]
sum = 40 for values greater than 12 : [2, 2, 13, 27, 9]

Related

fill two dimensional array with unique random number with java

Is there any way to fill two dimensional array with unique random number ? I tried so much but all of my tries are failed .
I can do this
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i < 26; i++) { //element will be in range (1,25)
list.add(i);
}
Collections.shuffle(list);
for (int j = 0; j < 5; j++) {
System.out.print(list.get(j) + " ");
}
System.out.println();
If you wanted to print a 5x5 matrix of numbers from the List, you just need two layers of for loops. See the below code in action here.
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i < 26; i++) { // element will be in range (1,25)
list.add(i);
}
Collections.shuffle(list);
for (int j = 0; j < 5; j++) {
for (int k = 0; k < 5; k++) {
System.out.format("%3d ", list.get(j * 5 + k));
}
System.out.println();
}
System.out.println();
Example Output:
3 4 23 18 15
1 8 20 6 7
5 21 19 2 24
17 13 22 16 25
14 9 12 10 11
I guess you can use combination of library which generates the random number and hashset. Hashset to remember the random number generated so far, and if duplicate is generated, you re-generate until it gives you the unseen number
Try this.
static List<List<Integer>> uniqueRandomNumbers(int height, int width) {
List<Integer> list = IntStream.rangeClosed(1, height * width)
.boxed()
.collect(Collectors.toList());
Collections.shuffle(list);
List<List<Integer>> matrix = IntStream.range(0, height)
.mapToObj(i -> list.subList(i * width, (i + 1) * width))
.collect(Collectors.toList());
return matrix;
}
and
List<List<Integer>> matrix = uniqueRandomNumbers(5, 5);
for (List<Integer> list : matrix)
System.out.println(list);
result
[16, 4, 15, 14, 25]
[19, 11, 6, 21, 9]
[17, 20, 3, 1, 5]
[10, 7, 22, 18, 2]
[12, 13, 24, 23, 8]
Does this can help ?
public static void main(String[] args)
{
// declare arrays
int[][] ticketInfo;
String[][] seatingChart;
// create arrays
ticketInfo = new int [2][3];
seatingChart = new String [3][2];
// initialize the array elements
ticketInfo[0][0] = 15;
ticketInfo[0][1] = 10;
ticketInfo[0][2] = 15;
ticketInfo[1][0] = 25;
ticketInfo[1][1] = 20;
ticketInfo[1][2] = 25;
seatingChart[0][0] = "Jamal";
seatingChart[0][1] = "Maria";
seatingChart[1][0] = "Jacob";
seatingChart[1][1] = "Suzy";
seatingChart[2][0] = "Emma";
seatingChart[2][1] = "Luke";
// print the contents
System.out.println(ticketInfo);
System.out.println(seatingChart);
}

Print only the numbers, which have been changed

I got curious about a Merge-sorting code.
Description:
This code creates two auxillary arrays left and right and store alternate array elements in them and then copying all elements of left and right subarrays back to original array and printing them. So instead of printing back to the original array, how would it be possible to only print the moved numbers?
class Project {
static void join(int arr[], int left[], int right[],int l, int m, int r){
int i;
for (i = 0; i <= m - l; i++)
arr[i] = left[i];
for (int j = 0; j < r - m; j++)
arr[i + j] = right[j];
}
static void split(int arr[], int left[], int right[],int l, int m, int r) {
for (int i = 0; i <= m - l; i++)
left[i] = arr[i * 2];
for (int i = 0; i < r - m; i++)
right[i] = arr[i * 2 + 1];
}
static void generateWorstCase(int arr[], int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;
int[] left = new int[m - l + 1];
int[] right = new int[r - m];
split(arr, left, right, l, m, r);
generateWorstCase(left, l, m);
generateWorstCase(right, m + 1, r);
join(arr, left, right, l, m, r);
}
}
public static void main (String[] args) {
int arr[] = { 10, 11, 12, 13, 14, 15, 16 };
int n = arr.length;
System.out.println("Sorted array is");
System.out.println(Arrays.toString(arr));
generateWorstCase(arr, 0, n - 1);
System.out.println("\nInput array that will result in worst case of merge sort is: \n");
System.out.println(Arrays.toString(arr));
}
}
Here's the output:
System.out.println(Arrays.toString(arr));
My question is..
I would ask, can you, based on the code, only have the output as, like the numbers being moved, and not the entire array?
Example:
The input is:
{ 10 20 30 40 50 }
The output is:
{ 10 50 30 20 40 }
My Desired Output:
{ 50 20 40 }
(The number of inputs varies according to the number of output)..
How would this happen?
Do it as follows:
public static void main(String[] args) {
int arr[] = { 10, 11, 12, 13, 14, 15, 16 };
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
map.put(arr[i], i);
}
int n = arr.length;
System.out.println("Sorted array is");
System.out.println(Arrays.toString(arr));
generateWorstCase(arr, 0, n - 1);
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
if (map.get(arr[i]) != i) {
list.add(arr[i]);
}
}
System.out.println("\nInput array that will result in worst case of merge sort is: \n" + list);
}
Output:
Sorted array is
[10, 11, 12, 13, 14, 15, 16]
Input array that will result in worst case of merge sort is:
[14, 16, 11, 13]
Another solution:
public static void main(String[] args) {
int arr[] = { 10, 11, 12, 13, 14, 15, 16 };
int[] original = Arrays.copyOf(arr, arr.length);
int n = arr.length;
System.out.println("Sorted array is");
System.out.println(Arrays.toString(arr));
generateWorstCase(arr, 0, n - 1);
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
if (original[i] != arr[i]) {
list.add(arr[i]);
}
}
System.out.println("\nInput array that will result in worst case of merge sort is: \n" + list);
}
Output:
Sorted array is
[10, 11, 12, 13, 14, 15, 16]
Input array that will result in worst case of merge sort is:
[14, 16, 11, 13]
[Update]
You have requested to change the format of the output so that the numbers are not bounded by []. Note that this is how Arrays.toString or List::toString returns the string. If you do not want an array or a List, you can do it simply as:
public static void main(String[] args) {
int arr[] = { 10, 11, 12, 13, 14, 15, 16 };
int[] original = Arrays.copyOf(arr, arr.length);
int n = arr.length;
System.out.println("Sorted array is");
System.out.println(Arrays.toString(arr));
generateWorstCase(arr, 0, n - 1);
StringBuilder s = new StringBuilder();
int i;
for (i = 0; i < arr.length; i++) {
if (original[i] != arr[i]) {
s.append(arr[i]).append(", ");
}
}
String output = s.substring(0, s.lastIndexOf(","));
System.out.println("\nInput array that will result in worst case of merge sort is: \n" + output);
}
Output:
Sorted array is
[10, 11, 12, 13, 14, 15, 16]
Input array that will result in worst case of merge sort is:
14, 16, 11, 13
If you want to change the format of the output while keeping the List, you can do it as follows:
public static void main(String[] args) {
int arr[] = { 10, 11, 12, 13, 14, 15, 16 };
int[] original = Arrays.copyOf(arr, arr.length);
int n = arr.length;
System.out.println("Sorted array is");
System.out.println(Arrays.toString(arr));
generateWorstCase(arr, 0, n - 1);
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
if (original[i] != arr[i]) {
list.add(arr[i]);
}
}
System.out.println("\nInput array that will result in worst case of merge sort is: \n"
+ list.toString().replace("[", "").replace("]", ""));
}
Output:
Sorted array is
[10, 11, 12, 13, 14, 15, 16]
Input array that will result in worst case of merge sort is:
14, 16, 11, 13
Iterate over both arrays simultaneously. If input[i] is not equal to output[i] then it has been moved.
List<Integer> moved = new ArrayList<>();
for (int i = 0; i < input.length; i++) {
if (input[i] != output[i]) {
moved.add(input[i]);
}
}

finding min & max in an array with 3 increments

I need to find the max and min for every 3 elements of a data using java array.
For double data[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14} , what is the max and min in every 3 elements? In other words, what is the max and min for {1,2,3}, {4, 5, 6}, {7, 8, 9}, etc.
I have the following method, but it is not getting the right results.
for (int i = 0; i < data.length; i+=3) {
for (int r = i; r < i + 3 && r < data.length; r++) {
if (data[r] < lowest) { lowest = data[r]; }
if (data[r] > highest) { highest = data[r]; }
}
lowest = highest;
highest = 0;
How about this?
int[] data = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
int processed = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < data.length; i++) {
if (data[i] < min) {
min = data[i];
}
if (data[i] > max) {
max = data[i];
}
processed++;
if (processed == 3) {
System.out.println("Min is: " + min);
System.out.println("Max is: " + max);
System.out.println("--------");
processed = 0;
min = Integer.MAX_VALUE;
max = Integer.MIN_VALUE;
}
}
Output:
Min is: 1
Max is: 3
--------
Min is: 4
Max is: 6
--------
Min is: 7
Max is: 9
--------
Min is: 10
Max is: 12
--------
It's unclear what to do with the numbers 13 and 14, as they don't form a block of 3, but I guess you get the idea of the algorithm.

sorting positive and negative integers through two integer arrays

We gave the following string:
int [] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87}.
There must be two rows, one for storage and the other positive elements for the negative elements of string array, and extracting the necessary logic that will perform the appropriate elements and placing them in the appropriate thread.
In other words, in the line array that is given is to be obtained all the positive elements and be placed in a separate row. Also, all the elements to be obtained and the negative to be placed in a separate row.
You also need to determine the number of duplicates in the string array.
Of course, it is necessary functionality written to be applicable to any number of integers. But MY teacher said that my code doesn't have a target row and He gave me an example: Target strings are two additional rows you will place isolated positive and negative values. For example, if you have a string:
int arr = {1,2,3,4, -1, -2, -3, -4}
then the target ranges will be:
int pos = {1,2,3,4}
int hc = {-1, -2, -3, -4}
of course, this should make it programmable and not hard coded, as in this example. Now how can I improve my code?
public static void main(String[] args) {
int array1[]= {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
System.out.println("Array 1 :");
Arrays.sort(array1);
for (int positive: array1) {
if (positive >= -1)
System.out.println("Positive numbers :" + positive+ "\t");
}
System.out.println();
System.out.println("Array 2 :");
for (int negative: array1) {
if (negative >= -1) {
}else{ System.out.println("Negative numbers :" +negative);
}
}
System.out.println();
for (int i = 0; i < array1.length -1; i++) {
if (array1[i + 1 ] == array1[i]) {
System.out.println("Duplicate element found :" + array1[i]);
i = i + 1;
}
}
}
}
If i have understood your question correctly, you want to make new arrays containing the positive and negative numbers,
Using your variable names i would go for something like this solution:
public static void main(String[] args) {
// Declare variables
int[] array1 = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87}, pos, hc;
int positive = 0, negative = 0;
// Check how many positive and/or negative numbers
for (int i : array1)
{
if (i >= 0)
{
positive++;
} else
{
negative++;
}
}
// Make exact size arrays
pos = new int[positive];
hc = new int[negative];
// Reset variables for new purpose
positive = 0;
negative = 0;
//Put numbers in correct array
for (int i : array1)
{
if (i >= 0)
{
pos[positive] = i;
positive++;
} else
{
hc[negative] = i;
negative++;
}
}
// Display arrays
System.out.print("Starter array: ");
for (int i: array1)
{
System.out.print(" " + i);
}
System.out.print("\nPositive array: ");
for (int i: pos)
{
System.out.print(" " + i);
}
System.out.print("\nNegative array: ");
for (int i: hc)
{
System.out.print(" " + i);
}
}
This outputs:
Starter array: 12 23 -22 0 43 545 -4 -55 43 12 0 -999 -87
Positive array: 12 23 0 43 545 43 12 0
Negative array: -22 -4 -55 -999 -87
try
int array1[]= {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
System.out.println("Array 1 :");
Arrays.sort(array1);
ArrayList<Integer> pos = new ArrayList<Integer>();
ArrayList<Integer> neg = new ArrayList<Integer>();
for (int num: array1){
if (num>= 0)
pos.add(num);
else
neg.add(num);
}
System.out.println();
if(pos.size()>0)
{
int[] positive = new int[pos.size()];
positive = pos.toArray(positive);
pos=null;
for (int num: positive)
System.out.println("Positive numbers :" + num+ "\t");
}
if(neg.size()>0)
{
int[] negative = new int[neg.size()];
negative = pos.toArray(negative);
neg=null;
for (int num: negative)
System.out.println("Negative numbers :" + num+ "\t");
}
for (int i = 0; i < array1.length -1; i++) {
if (array1[i + 1 ] == array1[i]) {
System.out.println("Duplicate element found :" + array1[i]);
i = i + 1;
}
}
sepratePositiveNegative(int[] arr) {
int size = arr.length;
int k =0;
for(int i =0;i <size; i++){
int temp = 0;
if(arr[i]<0) {
temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
k++;
System.out.println(arr[i]);
}
}

Java how to add int in an array using loop

i cant seem to figure out the logic, here's my code
class stringrays {
public static void main (String[] args) {
int[] numrays = {23, 6, 47, 35, 2, 14};
int i;
int z;
int y;
for (i=1; i < numrays.length; i++) {
z = numrays[0] + numrays[i];
System.out.println(z);
}
}
the above results shows
29
70
58
25
37
which means that array 0 adds array 1, then array 0 adds array array 2 and so on.
what i want, is to add the first array 0 onto the next array and so on.. using a loop condition.
then get the average of the sum.
Try this,
int[] numrays = {23, 6, 47, 35, 2, 14};
int z = 0;
for (int i=0; i < numrays.length; i++) {
z = z + numrays[i];
System.out.println(z);
}
System.out.println("Average : "+(z/numrays.length) );
}
If you mean 23, 6 then 6 + 47 and so on you need to do:
for (i=0; i < numrays.length - 1; i++)
{
z = numrays[i] + numrays[i + 1];
System.out.println(z);
}
Or the LambdaJ way :
int sum = sum(asList(1, 2, 3, 4, 5));
Remove numrays[0] and replace it with z
int z =0;
for (i = 0; i < numrays.length; i++) {
z = z + numrays[i];
System.out.println("Sum:"+z);
}
System.out.println("Average:"+z/numrays.length);
it is unclear what you need...
to add a value to the next position:
int[] numrays = {23, 6, 47, 35, 2, 14};
for(int i = 0; i < numrays.length - 1; i++) {
numrays[i] += numrays[i + 1];
}
System.out.println(Arrays.toString(numrays));
to get the mean value:
int[] numrays = {23, 6, 47, 35, 2, 14};
double sum = 0;
for(int i = 0; i < numrays.length; i++) {
sum += numrays[i];
}
double mean = sum / numrays.length;
System.out.println(mean);
You could use a "for each" loop, to sum the contents of the array and then find the average.
int sum = 0;
for(int each : numrays)
{
sum = sum + each;
}
float average = each / numrays.length;
Check your logic. Now you are printing sum of first and n-th number in array; old z value is lost. For sum in loop, use like z = z + something

Categories

Resources