Array with matrices table in Java - java

int [] arr = {-1,1,1,1,1}
int [] num = {23,24,25,26}
If I just want to sum {24,25,26}, how to call from arr[1,1,1,1}? For example: num 23 in index 0 of arr, num 24 in index 1 of arr and so on.
for (//..........) {
System.out.print (//.....)
}
Please note: array in arr is a table only. It does not mean summing, like a matrices table.

Here is the code I have come up with, you will need a method.
public int sum(int[] matrix, int ... args)
{
int sum = 0;
for(int index : args)
{
sum += matrix[index];
}
return sum;
}
This would basically take the matrix, then based upon any number of other arguments you gave, take the indexes and sum the values.

This will add the second array to the first, and ignore any items that are on indexes larger than the first array (for instance, if first array is {3, 4} and the second is {5, 3, 4} the 4 in the second array will be ignored).
private void sumArrays(int[] first, int[] second){
for(int i = 0; i < first.length; i++){
if(i >= second.length){
break;
}
first[i] += second[i];
}
}

If you are looking for the sum of your num array elements beginning from a parameter index then try this:
int [] num = {23,24,25,26};
public int CalculateSum(int index)
{
int sum =0;
if(index<num.length)
{
for(int i=index;i<num.length;i++) {
sum+=num[i];
}
}
return sum;
}

Related

How to build a random integer array of distinct elements? [duplicate]

This question already has answers here:
Generating Unique Random Numbers in Java
(21 answers)
Closed 1 year ago.
I am trying to create a method that fills an array with random integers with no duplicate elements. I'm having trouble making sure each element that is put into the new array is distinct.
Ex. if numOfDigits is 5, then I'd like something like [3][8][2][6][1]. At the moment it either outputs something like [9][0][1][0][0] or infinitely loops.
private static int[] hiddenSet(int numOfDigits){
int[] numArray = new int[numOfDigits];
int temp;
for (int i = 0; i < numArray.length; i++){
do {
temp = getRandomNum(10);
numArray[i] = temp;
} while (isDigitNew(numArray, temp));
//Each random num must be unique to the array
}
return numArray;
}
private static boolean isDigitNew(int[] numArray, int index){
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] == index) {
return false;
}
}
return true;
}
One easy approach is to fill the array with distinct digits then shuffle it.
public static int[] getRandomDistinct(int length) {
Random rand = new Random();
int[] array = new int[length];
// Fill with distinct digits
for (int i = 0; i < length; i++) {
array[i] = i;
}
// Swap every element with a random index
for (int i = 0; i < length - 1; i++) {
int swapWith = i + rand.nextInt(length - i);
int tmp = array[i];
array[i] = array[swapWith];
array[swapWith] = tmp;
}
return array;
}
Your algorithm takes quadratic time at best. When the choice of random numbers becomes less looping may take ages. Even infinite might be possible.
Add a positive random number + 1 to the previous generated number. The desired range of numbers needs a bit of care.
At he end shuffle. If you start with a List, you can use Collections. shuffle.
You can use IntStream like this.
private static int[] hiddenSet(int numOfDigits) {
return IntStream.iterate(getRandomNum(10), i -> getRandomNum(10))
.distinct()
.limit(numOfDigits)
.toArray();
}
and
public static void main(String[] args) {
int[] a = hiddenSet(5);
System.out.println(Arrays.toString(a));
}
output:
[7, 4, 5, 0, 1]

Array is being changed when in for statement

I think that it supposed to be posted with entire codes in this time.
When I'm trying to get values from Scanner into array named "score",
the second for statement shows unexpected outcomes.
import java.util.Scanner;
public class B1546 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int N = input.nextInt();
int[] score = new int[N];
Max scoreMax = new Max();
double sum = 0;
for (int i=0; i<N; i++) {
score[i] = input.nextInt();
}
for (int i=0; i<N; i++) {
System.out.println(score[i]); // this show the problems
sum = sum + ((double) score[i] / scoreMax.max(score) * 100);
}
System.out.println(sum / N);
}
}
class Max {
int max (int[] score) {
int[] tmpArray;
tmpArray = score;
for( int i=0; i<score.length-1; i++) {
for( int j=i+1; j<score.length; j++) {
if (tmpArray[i]<tmpArray[j]) {
int tmp = tmpArray[i];
tmpArray[i] = tmpArray[j];
tmpArray[j] = tmp;
}
}
}
return tmpArray[0];
}
}
For example, when I type
3
10 20 30
then It comes
10
20
10
...
not
10
20
30
...
I don't know what is the problem.
Your Max.max method changes the array - the 3 lines starting with int tmp =.
Likely the source of your problems is not understanding reference types. tmpArray = score does not make a separate copy of the array score -- you just have two references to the same array. This concept is fundamental to Java programming.
int max (int[] score) {
int[] tmpArray;
tmpArray = score;
}
score is a reference to the array object. Here you create a new reference to the existed array. To fix it, jut make a new array object:
int max(int[] score) {
int[] tmpArray = Arrays.copyOf(score, score.length);
}
int[] are objects and therefore are passed-by-reference in Java. When you do the following in your Max#max(int[]) method:
int[] tmpArray;
tmpArray = score;
Both tmpArray and score will hold the same reference, so when you swap values in the tmpArray, the score-array will be modified as well.
You'll have to create a new integer-array instead for the tmpArray, and copy the values. The simplest would be one of the following two:
int[] tmpArray = score.clone();
// or:
int[] tmpArray = Arrays.copyOf(score, score.length);
I would suggest the second, the .clone() is normally used for other purposes.
Try it online.

Rearrange an array in minimum and maximum java

Given an array of ints, I want to rearrange it alternately i.e. first element should be minimum, second should be maximum, third second-minimum, fourth second-maximum and so on...
I'm completely lost here...
Another method that doesn't require the space of three separate arrays but isn't as complex as reordering in place would be to sort the original array and then create a single new array. Then start iterating with a pointer to the current i-th index of the new array and pointers starting at the 0-th index and the last index of the sorted array.
public class Foo {
public static void main(String[] args) {
// Take your original array
int[] arr = { 1, 4, 5, 10, 6, 8, 3, 9 };
// Use the Arrays sort method to sort it into ascending order (note this mutates the array instance)
Arrays.sort(arr);
// Create a new array of the same length
int[] minMaxSorted = new int[arr.length];
// Iterate through the array (from the left and right at the same time)
for (int i = 0, min = 0, max = arr.length - 1; i < arr.length; i += 2, min++, max--) {
// the next minimum goes into minMaxSorted[i]
minMaxSorted[i] = arr[min];
// the next maximum goes into minMaxSorted[i + 1] ... but
// guard against index out of bounds for odd number arrays
if (i + 1 < minMaxSorted.length) {
minMaxSorted[i + 1] = arr[max];
}
}
System.out.println(Arrays.toString(minMaxSorted));
}
}
Hint:
Create two new arrays, 1st is sorted in assenting order and other is in descending order. Than select 1st element from 2nd array and 1st element from 1st array, repeat this selection until you reach half of both 1st and second array. and you will get your desired array.
Hope this will help you.
The approach in #Kaushal28's answer is the best approach for a beginner. It requires more space (2 extra copies of the array) but it is easy to understand and code.
An advanced programmer might consider sorting the array once, and then rearranging the elements. It should work, but the logic is complicated.
Hint: have you ever played "Clock Patience"?
This solution is based on Aaron Davis solution. I tried to make the looping easier to follow:
public class AltSort {
//list of array elements that were sorted
static Set<Integer> indexSorted = new HashSet<Integer>();
public static void main (String[] args) throws java.lang.Exception
{
//test case
int[] array = new int[]{7,22,4,67,5,11,-9,23,48, 3, 73, 1, 10};
System.out.println(Arrays.toString(altSort(array)));
//test case
array = new int[]{ 1, 4, 5, 10, 6, 8, 3, 9 };
System.out.println(Arrays.toString(altSort(array)));
}
private static int[] altSort(int[] array) {
if((array == null) || (array.length == 0)) {
System.err.println("Empty or null array can not be sorted.");
}
Arrays.sort(array);
//returned array
int[] sortedArray = new int[array.length];
int firstIndex = 0, lastIndex = array.length-1;
for (int i = 0; i < array.length; i++) {
if((i%2) == 0) { //even indices
sortedArray[i] = array[firstIndex++];
}
else {
sortedArray[i] = array[lastIndex --];
}
}
return sortedArray;
}
}
Here is another alternative: monitor the indices that have been sorted, and search the rest for the next min / max:
import java.util.Arrays;
import java.util.Set;
/**
* Demonstrates an option for sorting an int[] array as requested,
* by keeping a list of the array indices that has been sorted, and searching
* for the next min / max.
* This code is not optimal nor robust. It serves a demo for this option only.
*
*/
public class AltSort {
//list of array elements that were sorted
static Set<Integer> indexSorted ;
public static void main (String[] args) throws java.lang.Exception {
//test case
int[] array = new int[]{7,22,4,67,5,11,-9,23,48, 3, 73, 1, 10};
System.out.println(Arrays.toString(altSort2(array)));
//test case
array = new int[]{ 1, 4, 5, 10, 6, 8, 3, 9 };
System.out.println(Arrays.toString(altSort2(array)));
}
private static int[] altSort2(int[] array) {
if((array == null) || (array.length == 0)) {
System.err.println("Empty or null array can not be sorted.");
}
//returned array
int[] sortedArray = new int[array.length];
//flag indicating wether to look for min or max
boolean lookForMin = true;
int index = 0;
while(index < array.length) {
if(lookForMin) {
sortedArray[index] = lookForArrayMin(array);
}else {
sortedArray[index] = lookForArrayMax(array);
}
index++;
//alternate look for min / look for max
lookForMin = ! lookForMin;
}
return sortedArray;
}
private static int lookForArrayMin(int[] array) {
int minValue = Integer.MAX_VALUE;
int minValueIndex = 0;
for( int i =0; i< array.length; i++ ){
//if array[i] is min and was not sorted before, keep it as min
if( (array[i]< minValue) && ! indexSorted.contains(i) ) {
minValue = array[i]; //keep min
minValueIndex = i; //keep min index
}
}
//add the index to the list of sorted indices
indexSorted.add(minValueIndex);
return minValue;
}
private static int lookForArrayMax(int[] array) {
int maxValue = Integer.MIN_VALUE; //max value
int maxValueIndex = 0; //index of max value
for( int i =0; i< array.length; i++ ){
//if array[i] is max and was not sorted before, keep it as max
if( (array[i] > maxValue) && ! indexSorted.contains(i)) {
maxValue = array[i]; //keep max
maxValueIndex = i; //keep max index
}
}
//add the index to the list of sorted indices
indexSorted.add(maxValueIndex);
return maxValue;
}
}

Sum of Array using for loop returning 0

I have written this code below which should return the sum of an array. But it keeps returning 0. Please can someone help with this?
public class sumArray {
public static void main (String [] args) {
System.out.println(sumArrayof());
}
public static int sumArrayof(){
int k;
int sum = 0;
int[] bs = new int[20];
for (k=0; k<bs.length; k++) {
sum = sum + bs[k];
}
return sum;
}
}
Your method should receive an array as a parameter, instead of generating an array itself.
Like this:
public static int sumArrayof(int[] data) {
int k;
int sum = 0;
for (k=0; k<data.length; k++) {
sum = sum + data[k];
}
return sum;
}
The class, as written, isn't useful.
The method returns a zero because you're summing an array that has all zeroes in it. It's doing exactly what you asked it to do.
Maybe you meant to do something like this:
public class ArrayUtils {
public static void main (String [] args) {
if (args.length > 0) {
int [] values = new int[args.length];
for (int i = 0; i < args.length; ++i) {
values[i] = Integer.parseInt(arg);
}
System.out.println(ArrayUtils.sum(values));
}
}
public static int sum(int [] values) {
int sum = 0;
if (values != null) {
for (int value : values) {
sum += value;
}
}
return sum;
}
}
It is as expected.
You have made an empty array
int[] bs = new int[20];
// as good as
// int[] bs = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
which contains only zeroes.
Hence sum = 0
To fix you initialize array with initial values for eg
int[] bs = {1, 2, 3, 4 .......................};
Int array is only initialized. So default value is populated. So All the 20 elements are 0 only. So Iterating and adding 20 zero elements. So result is zero.
Your array is full of zeros.
Try something like that:
int[] bs = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
or initialize it some other way (like in another loop) or get it from main method input args.
Your array consists of 20 integers, but you never initialize them so they are 0.
int[] bs = new int[20];
System.out.println(Arrays.toString(bs)); // <-- 20 0s.
for (k=0; k<bs.length; k++) {
sum = sum + bs[k];
}
return sum;
20 * 0 is 0.
First you need to fill this array with some data.
As stated before you need to assign values to your array before summing them up.
You could do this: ps:altough you probably want to assign more meaningfull numbers ;) :
Random random = new Random();
public int getSomeValue(){
return random.nextInt(); // your logic to get a value
}
for (k=0; k<bs.length; k++) {
bs[k] = getSomeValue();
}
for (k=0; k<bs.length; k++) {
sum = sum + bs[k];
}

Removing specific value from array (java)

i have integer a = 4 and array b 7,8,9,4,3,4,4,2,1
i have to write a method that removes int ALL a from array b
desired result 7,8,9,3,2,1
This is what I have so far,
public static int[] removeTwo (int x, int[] array3)
{
int counter = 0;
boolean[] barray = new boolean [array3.length];
for (int k=0; k<array3.length; k++)
{
barray[k] = (x == array3[k]);
counter++;
}
int[] array4 = new int [array3.length - counter];
int num = 0;
for (int j=0; j<array3.length; j++)
{
if(barray[j] == false)
{
array4[num] = array3[j];
num++;
}
}
return array4;
I get this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Utility.removeTwo(Utility.java:50)
at Utility.main(Utility.java:18)
Java Result: 1
Any help would be much appreciated!
The error stems from this for loop:
for (int k=0; k<array3.length; k++)
{
barray[k] = (x == array3[k]);
counter++;
}
when you create int[] array4 = new int [array3.length - counter]; you are creating an array with size 0. You should only increment the counter if the item is the desired item to remove:
for (int k=0; k<array3.length; k++)
{
boolean b = (x == array3[k]);
barray[k] = b;
if(b) {
counter++;
}
}
To answer your question in the comment, the method should be called and can be checked like this:
public static void main(String[] args) {
int[] array3 = {0,1,3,2,3,0,3,1};
int x = 3;
int[] result = removeTwo(x, array3);
for (int n : result) {
System.out.print(""+ n + " ");
}
}
On this line:
int[] array4 = new int [array3.length - counter];
You create an array with size 0, as counter is equal to array3.length at this point.
This means that you cannot access any index in that array.
You are creating
int[] array4 = new int [array3.length - counter];// 0 length array.
you can't have 0th index there. At least length should 1 to have 0th index.
BTW my suggestion, it is better to use List. Then you can do this easy.
Really an Array is the wrong tool for the job, since quite apart from anything else you will end up with stray values at the end that you cannot remove. Just use an ArrayList and that provides a removeAll() method to do what you need. If you really need arrays you can even do:
List<Integer> list = new ArrayList(Arrays.asList(array))
list.removeAll(4);
array = list.toArray();
(Exact method names/parameters may need tweaking as that is all from memory).
the simplest way is to work with a second array where you put in the correct values
something likte that
public static int[] removeTwo (int x, int[] array3)
{
int counter = 0;
int[] array4 = new int[array3.lenght];
for (int i = 0; i < array3.lenght; i ++) {
if(array3[i] == x){
array4[counter] = array3[i];
}
}
return array4;
}
anoterh way is to remove the x calue from the array3 and shift the values behind forward
The best way to remove element from array is to use List with Iterator. Try,
Integer[] array = {7, 8, 9, 4, 3, 4, 4, 2, 1};
List<Integer> list = new ArrayList(Arrays.asList(array));
for(Iterator<Integer> it=list.iterator();it.hasNext();){
if(it.next()==4){
it.remove();
}
}

Categories