Define a Java method named weightedSum() that takes two integer arrays as its arguments. The
method uses a loop to multiply corresponding elements of the two arrays together (i.e., it multiplies the first argument of each array together, followed by multiplying the second element of each array together, and so on) and returns the sum of those products (which is also an integer). You may assume that both arrays are of equal length.
public int weightedSum(int [] a ,int [] b)
{
int value;
int sum ;
for (int i = 0 ; i < a.length ; i++)
{
value = a[i] * b [i];
value = value +value ;
}
return value;
I am having trouble writing this method out for my assignment . I under stand it accepts to arrays but i am having trouble writing out the loop itself so that it multiplies each individual element of the array with its counterpart in the opposite array so pos [1] * pos [1] and then add the two values togather with pos [2] + pos[2] and to get the sum total for all the values
below are the changes needed in your code. Basically you never updated the variable sum after you compute the product of corresponding elements in the two arrays. Also you might wanna use long type to store the result of the sum & the product as the int value might overflow if the elements in the array are sufficiently large.
public long weightedSum(int [] a ,int [] b)
{
long value = 0;
long sum = 0 ;
for (int i = 0 ; i < a.length ; i++)
{
value = a[i] * b [i];
sum = sum +value ;
}
return sum;
}
Try this:
public long dotProduct(int [] a, int [] b) {
if (a == null) throw new IllegalArgumentException("a array cannot be null");
if (b == null) throw new IllegalArgumentException("b array cannot be null");
if (a.length != b.length) throw new IllegalArgumentException("arrays must have equal lengths");
long sum = 0L;
for (int i = 0; i < a.length; i++) {
sum += a[i]*b[i];
}
return sum;
}
Most of the code looks correct, however the second line in the loop should not be changing the value variable, the sum variable should be updated with the value.
something like sum += value.
then return sum.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
System.out.println("Hello World");
System.out.println("Enter n :");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Integer[] arr = new Integer[n];
System.out.println("Enter Elements :");
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
//Ascending Array
Arrays.sort(arr);
System.out.println("Elements Are :");
for(int i=0;i<n;i++)
{
System.out.println(arr[i]);
}
//Descending Array
Arrays.sort(arr,Collections.reverseOrder());
System.out.println("Elements Are :");
for(int i=0;i<n;i++)
{
System.out.println(arr[i]);
}
//Product Of First Four Elements Of Array
int product=1;
for(int i=0;i<4;i++)
{
product=product*arr[i];
}
System.out.println("Product : "+product);
}
}
/* Output
Hello World
Enter n :
5
Enter Elements :
4
5
9
8
6
Elements Are :
4
5
6
8
9
Elements Are :
9
8
6
5
4
Product : 2160
*/
import java.util.*;
public class DemoNew
{
public static void main(String args[])
{
System.out.println("Hello World");
System.out.println("Enter N : ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Float[] r = new Float[n];
System.out.println("Enter Distances : ");
for(int i=0;i<n;i++)
{
r[i]=sc.nextFloat();
}
System.out.println("Distances : ");
for(int i=0;i<n;i++)
{
System.out.println(r[i]);
}
for(int i=0;i<r.length;i++)
{
if(r[i] == 0.0)
{
System.out.println("Invalid");
break;
}
else if(r[i] < 0)
{
System.out.println("Invalid");
break;
}
else
{
//Descending Array
Arrays.sort(r,Collections.reverseOrder());
System.out.println("Distances in Descending Order Are :");
for(int j=0;j<n;j++)
{
System.out.println(r[j]);
}
System.out.println("3 Max Distances Are :");
for(int k=0;k<3;k++)
{
System.out.println(r[k]);
}
List<Float> list = Arrays.asList(r);
System.out.println(list);
/* Float[] ar = new Float[r.length];
for(int m=0;m<r.length;m++)
{
ar[m]=r[m];
}
System.out.println("Final Ans :"); */
break;
}
}
}
}
Change to this:
value += a[i] * b [i];
// value = value + value;
Also initialize value to 0 before using it.
Also remove the sum variable.
Related
I was asked to
Create a method with a single parameter, an array of integers, that will return an array of integers. Count how many odd values exists within the array. Create a new array with that many elements. Place all the odd values into this new array ( that is all odd values from the array passed through as a parameter ). Return this new array
but I am having some difficulty in transferring the odd values into the new array. I can get the correct size based on the number of odd values in the first array but right now they appear as zeros. Here is the code:
import java.util.Scanner;
public class Main {
public static int output(int[]beans){
int sum = 0;
for (int p = 0; p < beans.length; p++){
if(beans[p]%2 != 0){
sum++;
}
}
System.out.print("The number of odd vaules in this array are: "+sum);
System.out.println();
int[] notbeans = new int[sum];
System.out.print("The odd values within the first array are: ");
for (int index = 0; index < beans.length; index++){
if( beans [index] %2 != 0){
System.out.print(beans[index]);
}
}
System.out.println();
for (int g = 0; g < notbeans.length; g++){
System.out.print(notbeans[g]);
}
return notbeans[1];
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
output(array);
}
}
According to your question, method output needs to...
Return this new array
Hence method output needs to return int[] (and not int).
After counting the number of odd values in the array passed to method output and creating the array that the method needs to return, in order to populate the returned array, you need to maintain a second [array] index. You are using the same index to populate the returned array and to iterate the array parameter. The returned array may be smaller in size, i.e. contain less elements, than the array parameter so using the same index for both arrays may cause method output to throw ArrayIndexOutOfBoundsException. In any method, you should also always check whether the method parameters are valid.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static int[] output(int[] beans) {
int sum = 0;
if (beans != null && beans.length > 0) {
for (int p = 0; p < beans.length; p++) {
if (beans[p] % 2 == 1) {
sum++;
}
}
}
int[] notBeans = new int[sum];
int j = 0;
for (int index = 0; index < beans.length; index++) {
if (beans[index] % 2 == 1) {
notBeans[j++] = beans[index];
}
}
return notBeans;
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[] array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
System.out.println(Arrays.toString(output(array)));
}
}
Your output function should return an array, so return type will not be int. It will be int[]. See the below code and let me know.
public class Main {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
int[] arr=output(array);
for(int i=0;i<arr.length;i++){
int val=arr[i];
if(val!=0){
System.out.println(val);
}
}
}
public static int[] output(int[]beans){
int[] notBeans=new int[beans.length];
int i=0;
for(int v:beans){
if(v%2!=0){
notBeans[i]=v;
i++;
}
}
return notBeans;
}
}
This question already has answers here:
Finding Duplicates in Array and printing them only Once
(6 answers)
Closed 4 years ago.
I have made the following program and implemented the merge sort where it sorts an array that the user fills and then picks any duplicate values from the array. However, I have a small problem in the main method. Example: I input the number 4 three times and it would display "duplicate: 4" two times; my goal here is to let it display only once, irrelevant of how many duplicates of 4 there are. Thanks guys.
import java.util.*;
`public class Question6` {
static void mergeSort(int arr1[], int o, int k, int x) {
int num1 = k - o + 1;
int num2 = x - k;
int temp1[] = new int [num1]; //creation of two temporary arrays to store in
int temp2[] = new int [num2];
for (int i=0; i<num1; ++i) //for loops to copy the data to the temporary arrays
temp1[i] = arr1[o + i];
for (int j=0; j<num2; ++j)
temp2[j] = arr1[k + o + j];
int i = 0, j = 0; //starting position of temporary arrays
int s = l; //starting position of the merged two temporary arrays
while (i < num1 && j < num2) {
if (temp1[i] <= temp2[j]) {
arr1[s] = temp1[i];
i++;
}
else {
arr1[s] = temp2[j];
j++;
}
s++;
}
//code to copy elements from temp1
while (i < num1)
{
arr1[s] = temp1[i];
i++;
s++;
}
//code to copy elements from temp2
while (j < num2)
{
arr1[s] = temp2[j];
j++;
s++;
}
}
/
void forSorting(int arr2[], int o, int x) //main method that carries out merge sort
{
if (o < x)
{
// Find the middle point
int a = (o+x)/2;
// Sort first and second halves
forSorting(arr2, o, a);
forSorting(arr2, a+1, x);
// Merge the sorted halves
mergeSort(arr2, o, a, x);
}
}
public static void main(String[] args) {
Question6 qs = new Question6();
Scanner sc = new Scanner(System.in);
int [] duplicate = new int[10];
System.out.println("Please input the numbers to be checked for repetition.");
for(int x = 0; x < 10; x++)
{
duplicate[x] = sc.nextInt(); //filling array
}
int length = duplicate.length;
qs.forSorting(duplicate, 0, length-1); //calling method forSorting
System.out.println(Arrays.toString(duplicate)); //displays array
for (int count = 1; count < 10; count++)
{
if (duplicate[count] == duplicate[count - 1]) {
//displays the duplicates
System.out.println("Duplicate: " + duplicate[count]);
}
}
}
}
I would try to go this way:
If the array has length 1, then there is no duplicate
If the array has length > 1, then iterate over the elements
The first element cannot be a duplicate
If the next element (assuming end of array not reached) has the same value as the current one, I have found a duplicate. Add the duplicate into something Set-like.
Continue with the next iteration.
After the iteration over the array is done, print all elements of the Set-like structure.
The type of input should be like 1, -9 ,6, -7, -4, 3
and there should be 2 outputs. First one 1 0 6 0 0 3
and second one 1 6 3:
import java.util.*;
class pr9 {
public static void calc() {
Scanner sc=new Scanner(System.in);
int x,i;
System.out.println("Enter Length of the Array");
x=sc.nextInt();
int a[]=new int[x];
int b[]=new int [x];
for(i=0;i<x;i++) {
System.out.println("Enter " +x+" Numbers");
a[i]=sc.nextInt();
}
for(i=0;i<x;i++) {
if(a[i]<0) {
a[i]=0;
}
System.out.print(a[i]+" ");
}
for(i=0;i<x;i++) {
if(a[i]!=0) {
a[i]=b[i];
}
System.out.print(b[i]);
}
}
}
}
This is how I did it but still in the second array where the zeroes should be eliminated , all are appearing zero.
Use this
import java.util.*;
class pr9
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int x,i,j;
int SECOND_ARRAY_SIZE = 0;
System.out.println("Enter Length of the Array");
x=sc.nextInt();
int a[]=new int[x];
for(i=0;i<x;i++)
{
System.out.println("Enter " +x+" Numbers");
a[i]=sc.nextInt();
if(a[i] > 0)
SECOND_ARRAY_SIZE++;
}
int b[]=new int [SECOND_ARRAY_SIZE];
for(i = 0, j = 0; i < x; i++)
{
if(a[i]<0)
a[i]=0;
else if(a[i] > 0)
{
b[j] = a[i];
j++;
}
}
// Easier to read
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
// What you want
for (int k = 0; k < a.length; k++) {
System.out.print(a[k] + " ");
}
System.out.println();
for (int l = 0; l < b.length; l++) {
System.out.print(b[l] + " ");
}
}
}
First of all, you are assigning to the wrong array :
a[i]=b[i];
should be
b[count]=a[i]; // note the different index
Second of all, when you assign to the second array, you must have two counters, since a[i] will not necessarily be assigned to b[i].
I suggest that you use the first loop to calculate how many non zero elements you have in the array, and create b with the correct length (otherwise it will contain 0s as its last elements) :
int bLength = 0;
for(i=0;i<x;i++)
{
if(a[i]<0)
{
a[i]=0;
} else {
bLength++;
}
System.out.print(a[i]+" ");
}
b = new int[bLength];
int count=0;
for(i=0;i<x;i++)
{
if(a[i]!=0)
{
b[count++] = a[i];
}
}
System.out.println(Arrays.toString(b));
I think this is your problem.
if(a[i]!=0)
{
a[i]=b[i];
}
System.out.print(b[i]);
}
b[] is never set so the values are all 0. You are checking each element of a[] and if its not equal to 0 you assign it to the value at b[] which is 0.
Ok, let's say that a[] is the array that should hold all values greater or equal than 0. This should work.
Your first problem is that the array that should hold all the positive numbers is as big as the entered amount of numbers. That's in most cases to big.
But if it doesn't matters that there are empty indizes in the array, your code should work if you replace the second loop with
if(a[i]!=0)
{
b[i]=a[i];
}
You did it the wrong way round (a[i] = b[i]).
How do I save it actually in the Array?
With this code it doesn't save anything in the array
I hope you can tell me more ways how to do it and explain in detail, thank you very much
import java.util.Scanner;
public class CountArray
{
public static void main(String[] arg)
{
Scanner scan = new Scanner(System.in);
int countPOZ = 0;
int countP5 = 0;
int countNONE = 0;
System.out.println();
System.out.print("Type elements: ");
int[] x = new int [scan.nextInt()];
for(int i = 0; i < x.length; i++)
{
System.out.print("Type numbers: ");
int numrat = scan.nextInt();
if(numrat > 0)
countPOZ++;
else if (numrat % 5 == 0)
countP5++;
else
countNONE++;
}
System.out.println();
System.out.println(x[1]); //here it will display 0 because nothing is saved.. in the array
System.out.println("Positive: "+countPOZ);
System.out.println("Div.. with 5: "+countP5);
System.out.println("Others: "+countNONE);
}
}
You store a value in the ith position of your x array with:
x[i] = someValue;
In the context of your loop :
for(int i = 0; i < x.length; i++)
{
System.out.print("Type numbers: ");
int numrat = scan.nextInt();
if(numrat > 0)
countPOZ++;
else if (numrat % 5 == 0)
countP5++;
else
countNONE++;
x[i] = numrat;
}
This stores the user's input in order.
x[i] = scan.nextInt();
Remove the local numrat and use x[i]. And please use braces, something like
x[i] = scan.nextInt();
if(x[i] > 0) {
countPOZ++;
} else if (x[i] % 5 == 0) {
countP5++;
} else {
countNONE++;
}
This is covered in and an example to JLS-10.4 - Array Access.
A component of an array is accessed by an array access expression (§15.13) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i].
All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.
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);
}
}
Try, add values in array then use array for business logic.
int[] x = new int [scan.nextInt()];
for(int i = 0; i < x.length; i++){
System.out.print("Type numbers: ");
x[i] = scan.nextInt();
if(x[i] > 0)
countPOZ++;
else if (x[i] % 5 == 0)
countP5++;
else
countNONE++;
}
But you missing something int[] x = new int [scan.nextInt()] as per your code you are not passing only one element and add that element to your array.
I assist pass multiple elements as comma separated list 1,2,3,4,5,6,7 then in your code you can create array list int x[] = scan.nextInt().split(",") then use it.
in your code
int[] x = new int [scan.nextInt()];
you are defining the size of an array. you are not storing any elements in here.
So define any elements in an array you have to access it's index and store your value in that specific index
x[1] = scan.nextInt()
can store the values in specific index
Without using collections,i have written a java program to remove duplicate integer element from an integer array,however the program is removing only one integer element and other integer element is left over.
Could you let me know how should i remove duplicate integer elements in the below core java program.In the below core java program i have to remove the duplicate integer element 5
Help provided will be appreciated.
Below is the Java code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DeleteElementFromArray {
static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[10];
static int i, k, f, j = 0;
static int l = a.length;
void DeletElementInt() {
for (i = 0; i < l; i++) {
if (i != k) {
if (i < k) {
b[i] = a[i];
} else{
b[i - 1] = a[i];
}
}
}
}
public static void main(String[] args) {
DeleteElementFromArray d = new DeleteElementFromArray();
System.out.println("Array Elements are ");
for (i = 0; i < l; i++){
System.out.println(a[i]);
}
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
System.out.println("Enter the Element for Delete");
try {
String s = br.readLine();
f = Integer.parseInt(s);
for (i = 0; i < l; i++) {
if (f == a[i]) {
System.out.println("Delete Element found from given array");
k = i;
j++;
d.DeletElementInt();
}
}
l = l - 1;
System.out.println("New Array ");
for (i = 0; i < l; i++)
{
System.out.println(b[i]);
}
if (j == 0) {
System.out.println("Entered Element does not found from given array");
}
} catch (IOException e) {
System.out.println(e);
}
}
}
//output
/*
Array Elements are
5
1
2
3
4
5
7
8
9
10
Enter the Element for Delete
5
Delete Element found from given array
New Array
1
2
3
4
5
7
8
9
10
*/
Here is the fixed code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DelElem {
static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[10];
static int f, i, k, j = 0;
static int l = a.length;
static void DeleteElementInt(int elementToDelete) {
j = 0;
for (int i = 0; i < l; i++)
if (a[i] != elementToDelete)
b[i - j] = a[i];
else
++j;
}
public static void main(String[] args) {
System.out.println("Array elements are:");
for (i = 0; i < a.length; i++)
System.out.println(a[i]);
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
System.out.print("Enter the element to be deleted: ");
try {
String s = br.readLine();
f = Integer.parseInt(s);
DeleteElementInt(f);
System.out.println("New array:");
for (i = 0; i < l - j; i++)
System.out.println(b[i]);
if (j == 0)
System.out.println("Entered element was not found in the given array");
} catch (IOException e) {
System.out.println(e);
}
}
}
//output
/*
Array elements are:
5
1
2
3
4
5
7
8
9
10
Enter the element to be deleted: 5
New array:
1
2
3
4
7
8
9
10
*/
First you have to sort your array. It will be much easier for you to remove the duplicates if you do. The Arrays class contains various methods (most of them are static) to manipulate arrays. Use Arrays.sort(array). If you're not allowed to, you have to use one of the many existing sorting algorithm. The simplest being Bubble sort.
Insert the first integer in your result array, and in a temporary variable which will contain the last inserted value. Parse the source array: if the current value is different than the temporary var, insert it in the result array (and update the temp var).
Be careful with the size of your return array.
is Arrays.sort() okay?
static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[a.length];
Arrays.sort(a);
b[0]=a[0];
int bIndex = 1;
for(int aIndex = 1; aIndex < a.length; aIndex++) {
if(b[bIndex-1] != a[aIndex]) {
b[bIndex] = a[aIndex];
bIndex++;
}
}
int[] result = Arrays.copyOfRange(b, 0, bIndex);
if this is for educational purposes another interesting approach could be to construct a tree structure with the numbers and flatten the tree to an array when all inserts are done.
The first question when some one ask you to work with arrays should be. Do the order is important ?
Most problem with arrays can be solved by sorting it first and then the problem is reduced to trivial from complex as you always work on the same type of data. As Archimedes sad once "Give me a place to stand on, and I will move the Earth". The sort operation is that stand place.
When you sort your array, then you just need to traverse it and find that next item is equal to previous. This is trivial.
How ever if the order is important then we have a little bit harder task.
So first solution that pop i my mind is to create new point to stand. The rules are that array has items grater or equal then zero.
In this case we could do something like this.
We find the grates element in our source array.
We create a boolean array with size of grates item.
We move through each item of source list and
We check that boolean arrays position of value has false if so then we set it to true an print the result else we go to next item of source array.
The step 4 was simplified as we want to print the list. The technical aspect of returning new one with distinct values is trivial to.
So good luck.
import java.util.Scanner;
public class RemoveAllOccurences{
static int[] removeAll(int[] a,int n){
int[] dupl = new int[a.length];
for(int i = 0;i < dupl.length;i++){
dupl[i] = -999;
}
int index = 0;
//looping over,finding all occurrences of n and creating new array that does not contain n.
for(int i = 0;i < a.length;i++){
if(a[i] != n){
dupl[index++] = a[i];
}
}
//returning array with all duplicates removed.
return dupl;
}
public static void main(String[] args) {
int[] a = {3,5,5,5,3,6,5,3,3};
int numberToRemove;
System.out.println("the array values are:");
for(int i:a){
System.out.print(a[i]+"\t");
}
Scanner sc = new Scanner(System.in);
System.out.println("\nenter the number for which all occurences need to be deleted:");
numberToRemove = sc.nextInt();
int[] b = removeAll(a,numberToRemove);
System.out.println("After removing all occurences of "+numberToRemove);
for(int i:b){
if(i != -999)
System.out.print(i+"\t");
}
}
}
Below is my solution:
First step:- Iterate through array with nested loops to find duplicates
Second step:- If found duplicates copy all elements in new array except duplicate element.
Please find below code, any improvement would be appreciated.
public class DuplicateElements {
private static int[] arr = new int[]{3,2,4,4,5,3,8,2,4,9,10};
public static void main(String[] args) {
for(int i=0;i<arr.length;i++){
int arr_i = arr[i];
for(int j=0;j<arr.length;j++){
if(arr_i == arr[j] && i != j){
removeElement(j);
}
}
}
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+", ");
}
}
public static void removeElement(int position){
int[] intArr = new int[arr.length - 1];
for(int i=0;i<position;i++){
intArr[i] = arr[i];
}
for(int i=position+1;i<arr.length;i++){
intArr[i-1] = arr[i];
}
arr = intArr;
}
}
public static void main(String[] args) {
int a[]={1,4,3,2,6,5,7,3,5,4,2};
int b[]=new int[a.length];
Arrays.sort(a);
int j=0;
for(int i=0;i<a.length;i++){
while(i<a.length-1 && a[i]==a[i+1]){
a[i]=999; // This can be any tag which you are not going to have in your array
i++;
}
if(a[i]!=999)
b[j++]=a[i];
}
System.out.println(b);
}
Use:
package Array;
import java.util.Scanner;
public class DuplicateArrayElement {
//operation
void duplicate(int arr[],int size) {
int count=0;
for(int i=0;i<size-1;i++) {
for(int j=i+1;j<size;j++) {
if(arr[i]==arr[j]) {
arr[i]=0;
count++;
}
}
}
for(int i =0; i<size;i++) {
if(arr[i]!=0) {
System.out.println(" "+arr[i]);
}
}
System.out.println("Total duplicate number : "+count);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DuplicateArrayElement duplicateArrayElement = new DuplicateArrayElement();
try {
System.out.println("Enter the size of array:");
int size = input.nextInt();
int arr[] = new int[size];
System.out.println("Enter the elements: ");
for (int i = 0; i < size; i++) {
arr[i] = input.nextInt();
}
System.out.println("Orignal Array: ");
for (int i : arr) {
System.out.print(" " + i);
}
System.out.println("\nAfter removing duplicate values :");
duplicateArrayElement.duplicate(arr, size);
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println(ex);
} finally {
input.close();
}
}
}