Say I have 10 integer variables, x1 to x10.
I have an integer array, as follows:
Int[] countup = new Int[10];
I would like to specify the elements of the array as follows:
countup[0] = x1;
countup[1] = x1 + x2;
countup[2] = x1 + x2 + x3;
And so on until countup[9] is the sum of x1 to x10.
I could do this manually if it was just 10 elements, but in the actual program I'm writing, there's over 100 elements of the array. Is there any way to set the variables of this array quickly?
A for loop is your best bet, simply put your 10 (or 100) integers into an array of it's own, then loop over your second array referencing indexes of the first array:
int[] xNumbers = { x1, x2, x3, ... x10 };
int[] countup = new int[10];
//Set the 0 index so we don't have to do extra check inside the for loop
//for out-of-bounds exception
countup[0] = xNumbers[0];
for (int i = 1; i < 10; i++) {
//countup[i-1] is why we set index 0 outside of the loop
countup[i] = xNumbers[i] + countup[i-1];
}
since countup[i-1] is the sum of the previous numbers, the previous additions are already done for you. In case you don't know what a for loop is, more information can be found here
Succinctly:
int[] xNums = { /*your x numbers here*/ };
int[] resultArray = new int[xNums.length];
for(int n = 0; n < xNums.length; n++)
{
for(int i = 0; i <= n; i++)
{
resultArray[n]+=xNums[i];
}
}
Hope that makes sense!
I wanted to find a way to do it in Java 8, and the other answer is probably better:
Here's what I have, but it seems redundant and a waste of time, but I'm unfamiliar with Java 8:
public static void main(String[] args) {
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int length = arr.length;
for (int i = 1; i < length; i++) {
System.out.println(Arrays.toString(Arrays.copyOfRange(arr, 0, i + 1)));
arr[i] = Arrays.stream(Arrays.copyOfRange(arr, 0, i + 1)).sum();
}
System.out.println(Arrays.toString(arr));
}
arr[9] is [1, 3, 7, 15, 31, 63, 127, 255, 511, 1023]
I believe I also interpreted the question differently. I think he wanted in index[i] the sum of all previous elements.
If my interpretation of your question is correct, to do it without Java 8, using 2 loops:
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int length = array.length;
for(int i = 1; i < length; i++) {
int sumSoFar = 0;
for(int j = 0; j <= i; j ++) {
sumSoFar += array[j];
}
array[i] = sumSoFar;
}
Related
I need to square the predefined array, but the problem is the iteration depends on what number the user enter is. I'm only new to java and do not know how it works.
int[] array = {1, 2, 3, 4, 5}; // Predefined array.
Scanner in = new Scanner(System.in);
int num = in.nextInt(); // Number of loop.
int sq = 0, sq2 = 0, sq3 = 0, sq4 = 0, sq5 = 0;
for (int i = 0; i < num; i++) {
sq = array[i] * array[i];
sq2 = array[i] * array[i];
sq3 = array[i] * array[i];
sq4 = array[i] * array[i];
sq5 = array[i] * array[i];
}
for (int i = 0; i < num; i++) {
System.out.println(sq);
System.out.println(sq2);
System.out.println(sq3);
System.out.println(sq4);
System.out.println(sq5);
}
Input:
1 //iteration
Output:
1
1
1
1
1
Expected output:
001
004
009
016
025
The value of i is 0 in the beginning. So all the values are actually storing the square of the 0th element that is the first element in the array which means they are all storing the square of "1".
Your code should be somewhat like this:
int[] array = {1, 2, 3, 4, 5}; // Predefined array.
Scanner in = new Scanner(System.in);
int num = in.nextInt(); // Number of loop.
int[] sq = {0, 0, 0, 0, 0};
for(int i = 0; i < num; i++)
{
for(int j = 0; j < 5; j++)
{
sq[j] = array[j] * array[j];
}
}
for(int i = 0; i < 5; i++)
{
System.out.println(sq[i]);
}
This should do the job.
to find the square of a number you can also use Math.pow(),
the num which it's value will be entered by user may cause problem so you need also to check that the value of i which is the index of array do not exceed from the arrays index
you need to use a printf to format the number output with leading zero:
int[] array = { 1, 2, 3, 4, 5 }; // Predefined array.
Scanner in = new Scanner(System.in);
int num = in.nextInt(); // Number of loop.
for (int i = 0; i < num && i < array.length; i++) {
System.out.printf("%03d\n", array[i] * array[i]);
}
You can use streams to square the elements of an array:
int[] array = {1, 2, 3, 4, 5};
// number of iterations
int i = 1;
// multiply each element of the array 'i' times
int[] squared = Arrays.stream(array)
.map(j -> IntStream.rangeClosed(0, i)
.map(k -> j)
.reduce(Math::multiplyExact)
.orElse(j))
.toArray();
// output
System.out.println(Arrays.toString(squared));
// [1, 4, 9, 16, 25]
See also: Returning a 2d array from inputed 1d array
I need help with a code where I have to put the number "7" at the front of the array using a random array of numbers. I use Math.random to generate the random numbers in each index. In any of these indexes, a number 7 may be generated.
import java.util.Arrays;
public class NumberShifter {
public static int[] Array(){
int[] array = new int[20];
int max = 10;
int min = 1;
int rand = 0;
int range = max - min +1;
for(int t = 0;t<=array.length-1;t++) {
rand = (int)(Math.random() * range) + min;
array[t] = rand;
}
return array;
}
}
Here's an example output for the code I have displayed (its all random numbers)
[9, 6, 3, 4, 4, 10, 7, 5, 2, 10, 3, 1, 8, 7, 4, 4, 10, 5, 9, 1]
There are two sevens in this array that have been generated randomly.
I would like to have the output where the sevens are at the front.
[7, 7, 3, 4, 4, 10, 9, 5, 2, 10, 3, 1, 8, 6, 4, 4, 10, 5, 9, 1]
How would I write the rest of my code so that I can achieve this?
P.S. I'm also in high school, so I'm sorry if I get something wrong!
Iterate the elements of the array and if they are 7 swap them with the next element at the beginning of the array, using another variable to keep track of the next index for swapping.
int index = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == 7) {
int tmp = array[i]; // actually not needed, we know it's 7
array[i] = array[index];
array[index] = tmp; // or just 7
index++;
}
}
I would actually start at the end and reserve the front for the sevens.
public static int[] Array() {
int[] array = new int[20];
int max = 10;
int min = 1;
int rand = 0;
int range = max - min + 1;
int sevensGoHere = 0;
for (int t = array.length - 1; t >= sevensGoHere;) {
rand = (int) (Math.random() * range) + min;
if (rand == 7) {
array[sevensGoHere++] = rand;
}
else {
array[t--] = rand;
}
}
return array;
}
By doing it on the fly you don't need to rearrange the array.
I have this integer array called numList which has
[4, 4, 3, 3, 3, 2, 1, 1, 1, 1, -1, -12, -12, -12, -12]
I would like to create a multidimensional array which can store
Which left side represents the number and the right side determines the number of occurrences.
The attempt i tried... i got nowhere.
// Declaring the new multi-dimensional array.
int [] [] newArray = new int [6] [2];
// Counter 3.
int counter3 = 0;
// Get first occurrence.
while (numList[counter3] < numList.length){
for (int counter3:numList){
newArray[] ([counter3]++);
}
Assuming your numbers are in order as they are in your example numList, then you could do this:
int[] numList = { 4, 4, 3, 3, 3, 2, 1, 1, 1, 1, -1, -12, -12, -12, -12 };
int[][] newArray = new int[6][2];
int index = 0;
for (int i = 0; i < numList.length;) {
int count = 0;
for (int x = 0; x < numList.length; x++)
if (numList[x] == numList[i]) count++;
newArray[index][0] = numList[i];
newArray[index][1] = count;
index++;
i += count;
}
for (int x = 0; x < newArray.length; x++) {
for (int i = 0; i < newArray[0].length; i++)
System.out.print(newArray[x][i] + " ");
System.out.println();
}
This way, you don't have to deal with imports as in the other answers (and this is shorter), but this only works if you have ordered numbers. There are some good sorting algorithms out there, though.
Edit: I changed it so that it can take numbers in any order of any size.
int[] numList = { 6, 6, 5, 5, 4, 4, 3, 2, 1, 1, 1, 7, 6, 5, 7, 8, 65, 65, 7 };
int[][] newArray = new int[1][2];
int index = 0;
for (int i = 0; i < numList.length;) {
try {
int count = 0;
boolean isUnique = true;
for (int x = 0; x < i; x++)
if (numList[x] == numList[i]) {
isUnique = false;
break;
}
if (isUnique) {
for (int x = 0; x < numList.length; x++)
if (numList[x] == numList[i]) count++;
newArray[index][0] = numList[i];
newArray[index][1] = count;
index++;
}
i++;
} catch (ArrayIndexOutOfBoundsException e) {
int tmpArray[][] = newArray;
newArray = new int[tmpArray.length + 1][tmpArray[0].length];
for (int row = 0; row < tmpArray.length; row++)
for (int col = 0; col < 2; col++)
newArray[row][col] = tmpArray[row][col];
}
}
for (int x = 0; x < newArray.length; x++) {
for (int i = 0; i < newArray[0].length; i++)
System.out.print(newArray[x][i] + " ");
System.out.println();
}
So, at this point, it would probably be shorter to use the maps from the other answer. The only benefit of my second answer not worrying about imports.
private Map<Integer, Integer> segregateArray(List<Integer> list) {
Map<Integer, Integer> result = new HashMap<>();
for (Integer i : list) {
if (result.containsKey(i)) {
result.put(i, result.get(i) + 1);
} else {
result.put(i, 1);
}
}
return result;
}
This should work. If you still need to return array use this:
private int[][] segregateArray(int[]list) {
Map<Integer, Integer> resultHelper = new HashMap<>();
for (int i : list) {
if (resultHelper.containsKey(i)) {
resultHelper.put(i, resultHelper.get(i) + 1);
} else {
resultHelper.put(i, 1);
}
}
int[][] result = new int[resultHelper.size()][2];
int arrayIterator=0;
for(Integer key : resultHelper.keySet())
{
result[arrayIterator][0]=key;
result[arrayIterator][1]=resultHelper.get(key);
arrayIterator++;
}
return result;
}
In the real life project you probably should avoid implementing a functionality like this yourself using a low level array mechanism (you added an extensive test suite, didn't you? :) and opt for one of available libraries.
In Java 8 this can be done nicely using closures similarly to what has been described here: Count int occurrences with Java8.
In Java 7 and earlier I would use one of the collection libraries such as Guava, which contains a Multiset collection delivering exactly what you're after.
How would one go about filling in an array so that, for example, if you had the following array.
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 3;
arr[2] = 7;
arr[3] = 2;
arr[4] = -4;
so it would look like
arr = {1, 3, 7, 2, -4};
and you would pass it into your method to get a result of
arr = {1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4};
so that you essentially are filling in the numeric gaps. I'd like to make this under the assumption that I don't know how long the array passed in is going to be to make it a more universal method.
my current method looks like such right now...
public static void fillArray(int[] numbers){
int length = numbers.length;
for(int i = 0; i < numbers.length - 1; i ++){
if(numbers[i] <= numbers[i + 1]){
length += numbers[i + 1] - numbers[i];
}else if(numbers[i + 1] < numbers[i]){
length += numbers[i + 1] - numbers[i];
}
}
}
I have length to determine the size of my new array. I think it should work but I'm always down for some input and advice.
Looks like homework, providing algorithm only:
Navigate through the elements of the current array.
Get the distance (absolute difference) between the elements in the array.
Summarize the distances.
Create a new array whose length would be the sum of the distances.
Fill the new array using the elements of the first array and filling the gaps.
Return the array.
Like Luiggi Mendoza said, looks like HW, so here's another algorithm:
insert the first element into a list of integers.
loop on the rest of the elements.
for each two array elements X[i-1], X[i], insert the missing integers to the list
after the loop - use guava to turn the List to array.
This works. just check for array size < 2 for safety.
public static void main(String[] args) {
int[] arr = {1, 3, 7, 2, -4};
Integer[] result = fillArray(arr);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
private static Integer[] fillArray(int[] arr) {
List<Integer> list = new ArrayList<Integer>();
list.add(arr[0]);
for (int i = 1; i < arr.length; i++) {
int prevItem = arr[i-1];
int gap = arr[i] - prevItem;
if(gap > 0){
fillGap(list, prevItem, gap, 1);
} else if(gap < 0){
fillGap(list, prevItem, gap, -1);
}
}
return list.toArray(new Integer[0]);
}
private static void fillGap(List<Integer> list, int start, int gap, int delta) {
int next = start+delta;
for (int j = 0; j < Math.abs(gap); j++) {
list.add(next);
next = next+delta;
}
}
Try
import java.util.ArrayList;
import java.util.List;
public class ArrayGap {
public static void main(String[] args) {
int[] arr = {1, 3, 7, 2, -4};
int high, low;
List<Integer> out = new ArrayList<Integer>();
for(int i=0; i<arr.length - 1; i++){
high = arr[i];
if(arr[i] < arr[i+1]){
for(int j=arr[i]; j<arr[i+1]; j++){
out.add(j);
}
} else {
for(int j=arr[i]; j>=arr[i+1]; j--){
out.add(j);
}
}
}
System.out.println(out);
}
}
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