How can I print all common numbers in three inputted user arrays? - java

int ar1, ar2, ar3;
System.out.print("Enter size of the 1st array: ");
//reading the number of elements from the that we want to enter
ar1 = sc.nextInt();
System.out.print("Enter value of the 1st array: ");
for (int i = 0; i < ar1; i++) {
array[i] = sc.nextInt();
}
System.out.println("Array1: ");
for (int i = 0; i < ar1; i++) {
System.out.println(array[i] + " ");
}
What can I add to print the common numbers in three inputted numbers in arrays?

first of all - arrays are primitive and quite a pain if it comes to using them. An alternative would be using ArrayList. But since you’re using arrays in this question, this would be an idea to solve the problem:
When your arrays are set up you can iterate through them to compare them. To do that you could declare 2 additional arrays:
int[] matchesA1A2 = new int[array1.length];
int[] matchesAll = new int[array1.length];
where machesA1A2 will contain the values that are both in array1 and array2. And matchesAll ALL the matching numbers.
Now just iterate through the first array comparing it with the second one to find which values match. Like that:
for (int i = 0; i<array1.length; i++){
for (int i2 = 0; i2<array2.length; i2++){
if (array1[i]==array2[i2]){
matchesA1A2[i] = array1[i];
}
}
}
The first two array are now compared. Now you can iterate through the third array comparing it witch the MATCHES of the array1 and array2 (which is the matchA1A2 array). Like this:
for (int i3 = 0; i3<array3.length; i3++){
for (int im = 0; im<matchesA1A2.length; im++){
if (array3[i3]==matchesA1A2[im]){
matchesAll[i3] = array3[i3];
}
}
}
If you println the matchesAll array you should see something, like this: [0, 0, 0, number, 0, 0, number, 0, 0…]
System.out.println(Arrays.toString(matchesAll));
Alle the “numbers” in the array are values that match in all three arrays.
Disclaimer: this is not the best way to write code, but I think because of the way it’s written it is easier for beginners to understand the concept of iterating.

Related

Why does this method only return values of 0 to a new array?

I am supposed to write a short program that takes 10 numbers, stores the values in an array, passes it to a method (eliminateDuplicates()) that creates a new array of only the unique values from the first array.
However, I am having trouble either initializing the output array, or making the eliminateDuplicates() method return the output array properly. The output array is always full of 0's and I cannot figure out why this is failing.
java.util.Arrays.parallelSort(inputNumbers); //sorts the array in ascending order
eliminateDuplicates(inputNumbers); //passes array to eliminateDuplicates method
//display each unique value in output array
System.out.print("The distinct numbers are ");
for(int i = 0; i < outputNumbers.length; i++)
System.out.print(outputNumbers[i] + " ");
}
public static int [] eliminateDuplicates(int[] list) {
int[] outputNumbers = new int [list.length];
int k = 0;
for (int i = 0; i < list.length; i++)
if(i == 0) //compares each array value against preceding value
outputNumbers[i] = list[i]; //only copies unique values to output array
else
if(list[i] != list [i-1]) {
outputNumbers[k] = list[i];
k++;
}
return outputNumbers;```
You have a local outputNumbers in eliminateDuplicates which you return. I assume you also have a redundant static outputNumbers. Option 1: Eliminate the local variable, change
int[] outputNumbers = new int [list.length];
to
outputNumbers = new int [list.length];
Option 2: Set outputNumbers on call (which is what I would likely do, and eliminate the static one)... Like,
int[] outputNumbers = eliminateDuplicates(inputNumbers);
Don't forget to remove the static one if you use option 2.
You are ignoring the array returned by your method.
Change
eliminateDuplicates(inputNumbers);
to
int[] outputNumbers = eliminateDuplicates(inputNumbers);
P.S. your output array has the same length as the input array. Therefore, since you are eliminating duplicates, it may have some 0s as its last elements. If that's not what you want, you should create the output array only after you find out how many unique numbers the input array has.

Take the values of an array and make them the indexes of another array in Java

How can I make the values of an array the index of another array? I am trying to count the different integers that were entered. When I run the code, I am getting an index out of bounds message. Any thoughts?
import java.util.Scanner;
public class MatchineNums{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] arr = new int[4];
System.out.print("Enter 4 numbers: ");
for(int i = 0; i < arr.length; i++){
arr[i] = input.nextInt();
}
int[] count = new int[arr.length];
for(int i = count.length; i > -1; i--){
int value = arr[i];
count[value]++; //I think my problem is here but can't figure out why.
}
}
}
You're getting index out of bounds exception because you're out-of-bound.
You need to start your loop from count.length - 1, not from count.length.
for (int i = count.length - 1; i > -1; i--) {...}
How can I make the values of an array the index of another array?
You cannot make indices. You can create an array big enough to have all the indices you need. Just keep the maximum value of your inputs and then create an array this size. Then you have an array with all these indices.
A better way to handle this problem is to use a hashmap. The keys will be the inputs and the values will be the counter of each of them. This way is better than an array because you have a map entry for each different input and that's it. Using an array you'll end up having a really sparse array with many "holes".

Creating a custom sort for an array of integers?

Right, so I have a 2 part sorting algorithm. It's all based on an array of 14 random integers. For example:
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
Now, the first thing I'm trying to figure out how to do is to count how many a certain number exists in the original array. So, we know that 1 exists once, and 2 exists four times in the original array. But as easy as it is to visually see this, what if we don't have access to the original array. So I need to craft a method that will count how many of each number 1-9 exists and put this in a new array called count. So that index 0 in count would represent the integer 1 and would have a value of 1. Index 1 will represent the integer 2 and have a value of 4. And so on and so forth. Here is what I've got so far but I'm stuck. Sorting is pretty challenging for me.
public static void main(String[] args)
{
// int[] countFinal = {1,4,1,2,1,0,1,2,2}; // The number of times a number 1-9 appears in a[].
// int[] sortedFinal = {1,2,2,2,2,3,4,4,5,7,8,8,9,9}; // What we need as a final product.
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
//int[] count = {};
int[] sorted = {};
countHowMany(a, 1);
countHowMany(a, 2);
countHowMany(a, 3);
countHowMany(a, 4);
countHowMany(a, 5);
countHowMany(a, 6);
countHowMany(a, 7);
countHowMany(a, 8);
countHowMany(a, 9);
}
public static int countHowMany(int[] array, int value)
{
// Gathering a count for how many times a number 1-9 exists and adding it to count[];
int howManyCount = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] == value)
{
howManyCount++;
}
}
System.out.println(howManyCount);
count = new int[9];
count[howManyCount];
System.out.println(Arrays.toString(count); // Testing the input
return howManyCount;
}
It appears to count the number of times an item in the array exists properly. Now I just gotta figure out how I can add that value into a new array count[] and do it for each countHowMany(). This is the part I'm stuck on.
Once I have figured out count[] I can use it to create sorted[]. Now what sorted is supposed to do is take the data from the original array and count[] and create a new array that sorts it in ascending order and allows duplicates. So, since 1 occurs once and 2 occurs four times, the new array would be sorted[] = {1, 2, 2, 2, 2, ...}
It's a relatively small program and a small amount of integers, so it's ok that I create array's as necessary. The key being that I'm limited to using arrays and cannot use say ArrayLists for this.
You don't need to count each value individually. You can just iterate through the entire array and increment your counters for each element as you encounter it.
int counts = new int[20]; // Choose a value that's bigger than anything in your array.
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
for (int value : a) {
counts[value]++;
}
If you don't know what the largest value in your array is likely to be, you're better to use either a Map to store the counts, or some kind of List that you increase the size of as needed.
You're better off just going through the array once and incrementing a counter for each value that might appear:
int counts[] = new int[10];
for (int n: array)
counts[n]++;
That's enough to put the count for each n in counts[n]. You can then read the values out of your count[] array.
You might not have come across this syntax for a for loop over an array, by the way. It's equivalent to
int counts[] = new int[10];
for (int i=0; i<array.length; i++) {
int n = array[i];
counts[n]++;
}
but it's less verbose.
Your method may as well be void, since you're not doing anything with the returned values of your countHowMany function. This will accomplish what you want:
public static void main(String[] args)
{
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
//count the instances of each number in the array
int[] count = new int[9];
for(int i = 0; i < count.length; i++)
count[i] = countHowMany(a, i+1);
//put the values in the sorted array
int[] sorted = new int[a.length];
int position = 0; // stores the place in the array to put the new digit
for(int digit = 0; digit < 9; digit++)
{
for(int inst = 0; inst < count[digit]; inst++)
{
sorted[position] = digit + 1;
position++;
}
}
System.out.println(Arrays.toString(sorted));
}
The issue with your code is that you were trying to create the count array in each call of the countHowMany method, but this array is destroyed once the method finishes. The method calls should just return the counts, and then those returns should be put into the count array from outside the method. Note, however, that there are other ways to count the number of instances of each value, as noted by other answers.

Sqrt, and Math in Arrays

I'm having difficulty understand how to write this array. I need it to out-print 10x5 (50 elements total), and have the first 25 elements equal to the sqrt of the index that it is in, and the last 25 to equal 3 * the index. Yes, this is homework but I'm not asking for you to do it for me, I just need help! I'm getting errors when using Math saying that I cant use double and the double array together. Here is what I have so far:
public class snhu4 {
public static void main(String args[]) {
double alpha[][] = new double[10][5];
double[] sum, sum2;
for (int count=0; count<=25;count++) {
alpha[count]= Math.sqrt(count);
}
for (int count=26; count<=50;count++) {
alpha[count]= count *3;
}
for (int count=0; count<=50;count++) {
System.out.print(alpha[count]);
}
}
}
Because alpha is a multidimensional array, you can't refer to its elements like a normal array.
int myarray[][] = new int[2][2];
In the above example, the array myarray is multidimensional. If I wanted to access the second element in the first array, I would access it like this:
int myint = myarray[0][1];
You are trying to access a multidimensional array by using the access for a normal array. Change
alpha[count]
to
alpha[0][count]
or similar.
Read here for more information on multidimensional arrays.
you defined alpha as a 2D array with lets say 10 items in the first dimension and 5 in the second, and 5x10 is 50 elements.
When using your array to assign values to these elements, u must call upon the array using 2 indices, one for each dimension:
alpha[i][j] = /*double value*/; //with 0<=i<=9 and 0<=j<=4
So the first 25 elements going from left to right in dimension order is going to be:
[0to9][0] and [0to9][1] and [0to4][2]
the next 25 will be
[4to9][2] and [0to9][3] and [0to9][4]
from then on i cannot give you the answers to your homework, but the loops should look like this:
int j;
for(int i = 0; i<25; i++)
{
j=i/10; //integer division will return 0 for i<10, 1 for 10<i<20, etc..
alpha[i%10][j] = Math.sqrt(i);
}
and you can figure out the rest
The 10x5 appears to be an output constraint, not a design constraint.
You are using Java, so use Java constructs, not C-language constructs;
specifically store the values in a List not an array.
Here are some hints:
List<Integer> valuesList = new ArrayList<Integer>();
for (int index = 0; index < 25; ++index)
Integer currentValue = Math.sqrt(index);
valuesList.add(currentValue);
for (int index = 25; index < 50; ++index)
Integer currentValue = index * 3;
valuesList.add(currentValue)
int count = 1;
for (Integer current : valuesList)
if ((count % 5) == 0) // write a newline.
System.out.print(current);
++count

Sort integer in Ascending Order - Java

I need help understanding how to sort numbers.
Below is what I have I came up with so far and it didn't work. Can you please point out the mistake and tell me what to do?
I saw some of you guys using java.util.Arrays . Can you describe to me its functions?
import static java.lang.System.*;
import java.util.*;
public class Lab07v2_Task10{
public static void main (String[] args){
Scanner orcho = new Scanner (in);
int quantity = 5;
int[] myArray = new int [quantity];
out.println("Please enter 5 numbers");
for(int count = 0; count<myArray.length; count++){
myArray[count] = orcho.nextInt();
}
int maxSoFar = myArray[0];
for(int count = myArray.length-1; count>=0; count--){
if(myArray[count] > maxSoFar){
maxSoFar = myArray[count];
}
out.println(maxSoFar);
}
}
}
No solution.
The idea is to take several steps, do a for-loop. And assume that you are in the middle. The first part already is sorted, the rest is to-be-done.
Then tackle the current element with respect to what already is sorted.
int maxSoFar = myArray[0];
for (int i = 1; i < myArray.length; i++) {
// The array 0, ..., i-1 is sorted
if (myArray[i] >= maxSoFar) {
// Still sorted
maxSoFar = myArray[i];
} else {
// myArray[i] must be shifted left
...
}
// Now the array 0, ..., i is sorted
}
This is a general trick: assume part is already done, tackle one small step, and let continue.
The java.util.Arrays.sort(int[]) method sorts the specified array of int into ascending numerical order.
try this out..
// sorting array
java.util.Arrays.sort(myArray);
// let us print all the elements available in list
System.out.println("The sorted int array is:");
for (int number : myArray) {
System.out.println("Number = " + number);
}
}
Arrays.sort is a method which is a utility method available in java.util package.
Where Arrays is a system defined Utility class which contains the mehtod sort(int[]) takes int[] (array) as an argument and after sorting this array, It re-assign Array.
For more deep Info Here or Official Java Docs
The way your program runs right now: it will print 5 numbers and the number that it prints is the highest number it finds at that iteration.
The way that you want it to work: sort 5 numbers from lowest to highest. Then print these 5 numbers. This is an implementation of bubble sort in your program:
for(int i = 0; i< myArray.length; i++){
for(int j = 0; j < myArray.length-1; j++){
if(myArray[j] > myArray[j+1]){ //if the current number is less than the one next to it
int temp = myArray[j]; //save the current number
myArray[j] = myArray[j+1]; //put the one next to it in its spot
myArray[j+1] = temp; //put the current number in the next spot
}
}
}
it is probably the easiest sort to understand. Basically, for as many times as the length of your array, comb over the numbers and bring the next highest number as far up as it can go.
When it's done sorting you can then print the numbers.

Categories