I have a set of 1d arrays that are being pulled from a method (tableMethod) - i want to grab those 1d arrays, then sum all the elements in each 1d array. How can I do that?
I have two loops
one that can sum a 1d array by itself
another that can display all the 1d arrays
I'm having difficulty combining the for loops so that it can grab each 1d array, sum it, then move on to the next 1d array, sum it, and so forth
the result should look something like:
total: 391
total: 393
total: 3903
total: 39104
total: 39031
... and so forth
int sum = 0;
int w = 0;
int[] arrayOne = tableMethod(table, w);
for (int k = 0; k < arrayOne.length; k++) {
sum = sum + arrayOne[k];
}
for (int i = 0; i < arrayOne.length; i++) {
System.out.println(Arrays.toString(tableMethod(table, i)));
}
System.out.println(sum);
}
Something like this would work,
import java.util.stream.IntStream;
int n = <max value of w>
int sum = 0;
for (int i = 0; i < n; i++) {
int[] array = tableMethod(table, i);
int arr_sum = IntStream.of(array).sum();
System.out.println(arr_sum); //single array sum
sum += arr_sum;
}
System.out.println(sum); //total sum
The code should be simply using nested loops (inner loop to calculate a sum may be replaced with stream):
int n = ... ; // a number of 1d arrays
int total = 0;
for (int i = 0; i < n; i++) {
int[] arr = tableMethod(table, i);
int sum = Arrays.stream(arr).sum();
System.out.println(sum);
total += sum;
}
System.out.println(total);
Related
I want to see how long it takes for 10,000 random integers to be sorted. Since in a bubblesort, the arrays are sorted at each stage and it could also vary each time, I want to know the total time it takes for the final sorting array to appear. So my time calculations should be when each sorting of the array is taking place, and when the final sorting happens and the results appear, the output should tell me the time in seconds.
I have used System.currentTimeMillis(); for this task but how would I use it so it calculates the time at each sorting stage? I have used it inside the for (int k = 0; k < numbers.length; k++){ loop because this loops through all the stages of the sorting, but my program would not output anything. How would I fix that?
Code:
class Main {
public static void main(String[] args) {
// Clear screen
System.out.print("\033[H\033[2J");
System.out.flush();
double msStartTime = 0d;
double msEndTime = 0d;
// Initialize an int array variable and set the limit to 10,000
int numbers[] = new int[10000];
// Generate random 10,000 integers to bubblesort
for (int x = 0; x < numbers.length; x++) {
numbers[x] = (int) (Math.random() * 10001);
}
for (int i = 0; i < numbers.length; i++) {
for (int j = i; j < numbers.length; j++) {
if (numbers[j] < numbers[i]) {
int temp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = temp;
}
}
for (int k = 0; k < numbers.length; k++){
msStartTime = (double) System.currentTimeMillis();
}
}
msEndTime = (double) System.currentTimeMillis();
System.out
.println("To sort an array of 10,000 integers, it takes " + (msEndTime - msStartTime) / 1000 + " seconds");
}
}
i think you can use StopWatch.here is how u can add it to maven and use it
https://www.baeldung.com/java-measure-elapsed-time
I'm trying to sort an array by the number of digits in each element from largest to smallest. This technically works but it seems to sort the array by value as well. For example, instead of printing out 1234 700 234 80 52, it should print 1234 234 700 52 80 as 234 is before 700 in the original array.
public class Sort {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {52, 234, 80, 700, 1234};
int temp = 0;
//Displaying elements of original array
System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
//Sort the array in descending order
//Math function is used to find length of each element
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(Math.log10(arr[i]) + 1 < Math.log10(arr[j]) + 1) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println();
//Displaying elements of array after sorting
System.out.println("Elements of array sorted in descending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
The easiest way to find the length of the number is to convert it into a String and then call the method length on it.
int number = 123;
String numberAsString = String.valueOf(number);
int length = numberAsString.length(); // returns 3
But you also could do it by division. The following method takes a number and divides by multiples of 10.
divide by 1 (we have at least a length of 1)
division by 10 > 0 (we have at least a length of 2)
division by 100 > 0 (we have at least a length of 3)
...
the variable i is used as dividend and the variable j is used as counter. j counts the length of the number.
As soon as number / i equals zero we return the counter value.
public int lengthOfNumber(int number) {
if (number == 0) {
return 1;
}
for (int i = 1, j = 0; ; i *= 10, j++) {
if (number / i == 0) {
return j;
}
}
}
There are multiple ways to sort the array. Here are some examples (I used the string version for comparing the values).
Use nested for-loop
public void sortArray(int[] array) {
for (int i = 0; i < array.length; i++) {
int swapIndex = -1;
int maxLength = String.valueOf(array[i]).length();
for(int j = i + 1; j < array.length; j++) {
int length2 = String.valueOf(array[j]).length();
if (maxLength < length2) {
maxLength = length2;
swapIndex = j;
}
}
if (swapIndex > -1) {
int temp = array[i];
array[i] = array[swapIndex];
array[swapIndex] = temp;
}
}
}
I used a variable swapIndex which is initialized with -1. This way we can avoid unnecessary array operations.
We take the first element in the outer for-loop and go through the rest of the array in the inner for-loop. we only save a new swapIndex if there is a number in the rest of the array with a higher length. if there is no number with a higher length, swapIndex remains -1. We do a possible swap only in the outer for-loop if necessary (if swapIndex was set).
Using Arrays.sort()
If you want to use Arrays.sort you need to convert your array from primitive type int to Integer.
public void sortArray(Integer[] array) {
Arrays.sort(array, (o1, o2) -> {
Integer length1 = String.valueOf(o1).length();
Integer length2 = String.valueOf(o2).length();
return length2.compareTo(length1);
});
}
Using a recursive method
public void sortArray(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
String current = String.valueOf(array[i]);
String next = String.valueOf(array[i + 1]);
if (current.length() < next.length()) {
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
// here you do a recursive call
sortArray(array);
}
}
}
I need to sum of x element together in order from an array and insert the result in new array.
For example,
int x = 3;
int [ ]array = {1,2,5,8,4,9,4,2,9,7,5}; //we have 11 element here
int [ ]newarray= new int [Math.round(array.length/x)]; // the size will be round(11/3)= 4
The size of newarray will be 4
int sum = 0 ; // this will hold the sum of the array element
I need loop into array and sum the first **(x)**three elements and insert the summation in the first newarray index and empty sum variable
then loop again in the array starting from the next three element and insert the summation in the second index of the newarray and so on..
the last index of the new array will be summation of the last two element from array because there is only two element in the array
we get the some and insert it to the last index of the array the array should look like that
for (int i=0; i< newarray.length;++i){
System.out.println(newarray[i]);
Expected output should be
newarray [ 0 ]= 1+2+5 = 8
newarray [ 1 ]= 8+4+9 = 21
newarray [ 2 ]= 8+4+9 = 15
newarray [ 3 ]= 7+5 = 12
Need a solution.
First you need to cast the x to double, because int/int will result in int so you will never get the space last for holding the partial sum. Use the ceil() function not the round(). Because round() converts the input to the closest integer, where as you need closet upper integer.
int []newarray= new int [(int) Math.ceil(array.length / (double)x)];
Use two loops and put the sum in array. First, iterates over the sum result array (where you are storing the sum) and second to fetch the element from the source array.
When the source array does not have element in the multiples of x make sure you don't access the extra unavailable elements, otherwise exception will be thrown.
for (int i=0; i<newarray.length; i++) {
int sum = 0;
for(int j=0; j<x && x*i+j < array.length; j++) {
sum += array[x*i+j];
}
newarray[i] = sum;
}
// print the results
for (int xx : newarray) {
System.out.println(xx);
}
Try folowing code:
It can be done with reduced complexity having just the one loop:
int x=3;
int [ ]array = {1,2,5,8,4,9,4,2,9,7,5};
int [ ]newarray= new int [(int) Math.ceil(array.length / (double)x)];
int sum=array[0],k=0;
for (int i=1; i< array.length;i++){
sum=sum+array[i];
if((i+1)%3==0){
newarray[k]=sum;
System.err.println(newarray[k]);
sum=0;
k++;
}else if(i+1==array.length){
newarray[k]=sum;
System.err.println(newarray[k]);
}
}
Output:
8
21
15
12
Here is the solution you want,
int ind = 0, sum;
for (int i = 0; i < array.length; i += 3)
{
sum = 0;
for(int j = 0; j < 3 && i + j < array.length; j++)
{
sum = sum + array[i + j];
}
newarray[ind++] = sum;
}
Now newarray contains what you want.
i have an array of integer arrays 'int pixels[][]'
and i want to find the sum of all of them so i can find the average pixel value
this will be used so that i can set the average value of a pixel to be the threshold value for a pbm image
if the value if above threshold i will export a white pixel if its below i will export a black one (just to give some context)
i assume the code below is not correct at all as the output it 6.0 but i think its something like this
double threshold = 0;
for(int i = 0; i < pixels.length; i++)
{
threshold += (double)pixels[i][i];
}
System.out.print(threshold);
Do you want to iterate all number in arrays,you can try with this:
double threshold = 0;
for(int i = 0; i < pixels.length; i++)
{
for(int j=0;j<pixels[i].length;j++){
threshold += (double)pixels[i][j];
}
}
System.out.print(threshold);
HINT
You have a 2D array, So to add each element you need to traverse each column of each row. For this 2 for loops might be of some use.
traverse over each value and add them
exit loop
Divide your sum with number of elements to get average (you may need to give some thought to type casting here)
You need to iterate over each row and column in the array, so you need 2 for-loops. What you're currently doing only covers the following: (0,0), (1,1), (2,2), ....
This would work: (assuming a non-jagged array, at least for the threshold calculation)
long sum = 0;
for (int i = 0; i < pixels.length; i++)
for (int j = 0; j < pixels[i].length; j++)
{
sum += pixels[i][j];
}
double threshold = (double)sum / (pixels.length * pixels[0].length);
System.out.print(threshold);
Or more simply: (assuming a non-jagged array, at least for the threshold calculation)
long sum = 0;
for (int[] i: pixels)
for (int j: i)
{
sum += j;
}
double threshold = (double)sum / (pixels.length * pixels[0].length);
System.out.print(threshold);
You need to use a double for here. Something like this:-
for(int i = 0; i < pixels.length; i++){
for(int i = 0; i < pixels[i].length; i++){
threshold += (double)pixels[i][j];
}
}
you dont need a double when you count sum of ints, this is a waste, use long, it's faster
long sum = 0;
int n = 0;
for (int[] a : pixels) {
for (int e : a) {
sum += e;
n++;
}
}
double avg = ((double) sum) / n;
I need to create an array with 100 numbers (1-100) and then calculate how much it all will be (1+2+3+4+..+100 = sum).
I don't want to enter these numbers into the arrays manually, 100 spots would take a while and cost more code.
I'm thinking something like using variable++ till 100 and then calculate the sum of it all. Not sure how exactly it would be written.
But it's in important that it's in arrays so I can also say later, "How much is array 55" and I can could easily see it.
Here's how:
// Create an array with room for 100 integers
int[] nums = new int[100];
// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
nums[i] = i + 1; // +1 since we want 1-100 and not 0-99
// Compute sum
int sum = 0;
for (int n : nums)
sum += n;
// Print the result (5050)
System.out.println(sum);
If all you want to do is calculate the sum of 1,2,3... n then you could use :
int sum = (n * (n + 1)) / 2;
int count = 100;
int total = 0;
int[] numbers = new int[count];
for (int i=0; count>i; i++) {
numbers[i] = i+1;
total += i+1;
}
// done
I'm not sure what structure you want your resulting array in, but the following code will do what I think you're asking for:
int sum = 0;
int[] results = new int[100];
for (int i = 0; i < 100; i++) {
sum += (i+1);
results[i] = sum;
}
Gives you an array of the sum at each point in the loop [1, 3, 6, 10...]
To populate the array:
int[] numbers = new int[100];
for (int i = 0; i < 100; i++) {
numbers[i] = i+1;
}
and then to sum it:
int ans = 0;
for (int i = 0; i < numbers.length; i++) {
ans += numbers[i];
}
or in short, if you want the sum from 1 to n:
( n ( n +1) ) / 2
If your array of numbers always is starting with 1 and ending with X then you could use the following formula:
sum = x * (x+1) / 2
from 1 till 100 the sum would be 100 * 101 / 2 = 5050
this is actually the summation of an arithmatic progression with common difference as 1. So this is a special case of sum of natural numbers. Its easy can be done with a single line of code.
int i = 100;
// Implement the fomrulae n*(n+1)/2
int sum = (i*(i+1))/2;
System.out.println(sum);
int[] nums = new int[100];
int sum = 0;
// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
{
nums[i] = i + 1;
sum += n;
}
System.out.println(sum);
The Array has declared without intializing the values and if you want to insert values by itterating the loop this code will work.
Public Class Program
{
public static void main(String args[])
{
//Array Intialization
int my[] = new int[6];
for(int i=0;i<=5;i++)
{
//Storing array values in array
my[i]= i;
//Printing array values
System.out.println(my[i]);
}
}
}