I am trying to compare two arrays inside For Loops - java

I am creating a Lottery Program where I want to compare the winning numbers with the players numbers and if any numbers match, they win a prize. I have used count to do this in my match() method but it comes up with an error when I try to compare two arrays - getWinningNumbers() and getNumbers() which are from the other classes PLAYER and WINNINGNUMBERS. The error I am getting is "actual and formal parameters differ in length" but I am unsure how to fix this. I am using linked lists for the first time as well. Any help would be much appreciated.
The piece of code I am having trouble with is in the method match() in the Lottery Class.
public void matches() {
PLAYER currentPlayer = pHead;
int count = 0;
for(int i = 0; i<6; i++) {
for(int j = 0; j< 6; j++) {
if (win.getWinningNumbers(i) == currentPlayer.getNumbers(j)) {
count++;
}
}
}
``````````````````````````````````````````````````````````````````````````

Change the following snippet in matches():
if (win.getWinningNumbers(i) == currentPlayer.getNumbers(j)) {
count++;
}
To
if (win.getWinningNumbers()[i] == currentPlayer.getNumbers()[j]) {
count++;
}

Maybe this example can help you a bit:
List<Integer> winningNumber = new LinkedList<>(Arrays.asList(3, 9, 15, 1, 11, 18));
List<Integer> playerNumbers = new LinkedList<>(Arrays.asList(2, 8, 15, 7, 11, 9));
matches(winningNumber, playerNumbers);
private static void matches(List<Integer> winningNumbers, List<Integer> playerNumbers) {
if(winningNumbers.size() != playerNumbers.size()) {
System.out.println("winning numbers and player numbers differ in size");
}
int counter = 0;
for(int i = 0; i < winningNumbers.size(); i++) {
if(winningNumbers.get(i) == playerNumbers.get(i)) {
counter++;
}
}
System.out.println("Number of matches in position: " + counter);
// if the position of match is not important
long matches = winningNumbers.stream()
.filter(playerNumbers::contains)
.count();
System.out.println("Number of matches: " + matches);
}
Number of matches in position: 2
Number of matches: 3

Related

Counting the number of common elements in integer arrays located at different positions

For my assignment, I need to write a method that returns the number of cows (see definition below) found between 2 arrays. If the input arrays have a different number of elements, then the method should throw an IllegalArgumentException with an appropriate message.
A bull is a common number in int arrays found at the same position while a cow is a common number in int arrays found at different position. Note that if a number is already a bull, it cannot be considered as a cow.
For example, considering the following arrays:
int[] secret = {2, 0, 6, 9};
int[] guessOne = {9, 5, 6, 2};
int[] guessTwo = {2, 0, 6, 2};
int[] guessThree = {1, 2, 3, 4, 5, 6};
int[] guessFour = {1, 3, 4, 4, 0, 5};
1) getNumOfCows(secret, guessOne) returns 2
2) getNumOfCows(secret, guessTwo) returns 0
3) getNumOfCows(secret, guessThree) returns an exception
4) getNumOfCows(guessThree, guessFour) returns 2
My method seen below works perfectly for examples 1 and 3, but there is a problem with examples 2 and 4 such that getNumOfCows(secret, guessTwo) returns 1 instead of 0 because the element at secret[0] and guessTwo[3] is considered a cow. Could anybody help me fix my code?
// A method that gets the number of cows in a guess --- TO BE FIXED
public static int getNumOfCows(int[] secretNumber, int[] guessedNumber) {
// Initialize and declare a variable that acts as a counter
int numberOfCows = 0;
// Initialize and declare an array
int[] verified = new int[secretNumber.length];
if (guessedNumber.length == secretNumber.length) {
// Loop through all the elements of both arrays to see if there is any matching digit
for (int i = 0; i < guessedNumber.length; i++) {
// Check if the digits represent a bull
if (guessedNumber[i] == secretNumber[i]) {
verified[i] = 1;
}
}
for (int i = 0; i < guessedNumber.length; i++) {
// Continue to the next iteration if the digits represent a bull
if (verified[i] == 1) {
continue;
}
else {
for (int j = 0; j < secretNumber.length; j++) {
if (guessedNumber[i] == secretNumber[j] && i != j) {
// Update the variable
numberOfCows++;
verified[i] = 1;
}
}
}
}
}
else {
// Throw an IllegalArgumentException
throw new IllegalArgumentException ("Both array must contain the same number of elements");
}
return numberOfCows;
}
First go through and mark all bulls using a separate array to make sure a position that is a bull also get counted as a cow
public static int getNumOfCows(int[] secretNumber, int[] guessedNumber) {
int max = secretNumber.length;
int cows = 0;
int[] checked = new int[max];
for (int i = 0; i < max; i++) {
if (secretNumber[i] == guessedNumber[i]) {
checked[i] = 1;
}
}
for (int i = 0; i < max; i++) {
if (checked[i] == 1) {
continue;
}
for (int j = 0; j < max; j++) {
if (secretNumber[i] == guessedNumber[j]) {
cows++;
checked[i] = 1;
}
}
}
return cows;
}
Now that this answer is accepted the original question can be voted to be closed as a duplicate
I am posting my answer from a duplicate question here and if this get approved then the other one can get closed as a duplicate.
The problem is that an element that is multiple times in at least one array will not be handled correctly.
A possible solution idea might be this one:
Create a cow list.
Iterate through both arrays and add every element that is in both arrays and has not been added yet. (note: complexity is n²)
Now that all possible cows are in the list, iterate through the array positions with the same index and if you find a bull, remove the number from the cow list.
Now the cow list contains only cows.
This solution might be a bit slower than your current one, but I think it's working properly.

JAVA: Replacing number in array, with the numbers position and print out

I have a small problem here. I want to replace all negative numbers in an array with the numbers position. My problem is that the array gets printed out, before the numbers are replaced, and I want to print out the array after it gets replaced...
Here is my code:
public class oppgave33{
public static void main(String[] args) {
int[] heltall = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int counter = 0;
int sumNeg = 0;
while(counter < heltall.length){
//array print out
System.out.println("array[" + counter + "] = " + heltall[counter]);
if(heltall[counter] < 0){
System.out.println(heltall[counter]);
}
//replacing negative numbers
if(heltall[counter] < 0 ){
heltall[counter]=counter;
}
if(heltall[counter] < 0){
sumNeg++;
}
//negative numbers position print out
if(heltall[counter] < 0 ){
System.out.println("Negative numbers position in array is : " + counter);
}
counter++;
}
//printing out how many negative numbers
System.out.println("There are : " + sumNeg + " negative numbers.");
}
}
Final note: if you remove the if setting, where the negative numbers are replaced by their position in array, you will get position to negative numbers printed out, and also how many negative numbers there are.
I hope you can help me! :) Thank you!
You have too many redundant conditions in your code. Your attempt is very close, you can simply do the following:
while (counter < heltall.length) {
// if the number is negative, replace it with its index
if (heltall[counter] < 0) {
heltall[counter] = counter;
}
counter++;
}
// outside the loop
System.out.println(Arrays.toString(heltall));
Important tip: In such cases, you should debug your code. This will help you better understanding the flow of your code, and discover problems that you're not aware of them. I highly recommend you debugging your current code, and only then try to fix it.
Here is the working version of your code:
Note: You must place the printing command after the replacement. Code runs step-by-step and in the line order. The statements at the top rows run first, then the lower rows, (sure in order).
public class oppgave33{
public static void main(String[] args) {
int[] heltall = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int counter = 0;
int sumNeg = 0;
while(counter < heltall.length){
if(heltall[counter] < 0 ){
//replacing negative numbers
heltall[counter]=counter;
//counting negative number amount
sumNeg++;
//array print out after replace
System.out.println("array[" + counter + "] = " + heltall[counter]);
//negative numbers position print out
System.out.println("Negative numbers position in array is : " + counter);
}
counter++;
}
//printing out how many negative numbers
System.out.println("There are : " + sumNeg + " negative numbers.");
}
}
You don't need that much of conditions to replace negative numbers. Just replace one by one when you get a negative number in the loop.
Removing redundancy: One thing to remember: when you have some statements for same condition, you don't need to do them individually. Write all the statements in same if block.
For example, in your code:
if (heltall[counter] < 0) {
System.out.println(heltall[counter]);
}
if (heltall[counter] < 0) {
heltall[counter] = counter;
}
if (heltall[counter] < 0) {
sumNeg++;
}
if (heltall[counter] < 0) {
System.out.println("Negative numbers position in array is : " + counter);
}
Could be replaced by:
if(heltall[counter] < 0) { // do all in the same if condition block
System.out.println(heltall[counter]);
heltall[counter] = counter;
sumNeg++;
System.out.println("Negative numbers position in array is : " + counter);
}
Solution: Anyway, the whole code could look like this:
while (counter < heltall.length) {
// replacing negative numbers
if (heltall[counter] < 0) {
heltall[counter] = counter;
sumNeg++;
}
counter++;
}
System.out.println("There were : " + sumNeg + " negative numbers.");
System.out.println("Array after replacing negative numbers: "+Arrays.toString(heltall));

Finding missing elements in arrays

My program is : In an array 1-10 numbers are stored, one number is missing how do you find it?
I have tried the following code, but it is not giving the right output.
public class MissingNumber {
public static void main(String[] args) {
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 9, 9, 10 };
System.out.println(arr.length);
int arr2[] = new int[10];
for (int i = 0; i < arr2.length; i++) {
arr2[i] = i + 1;
System.out.println("second array is : " + arr2[i]);
}
//compare two arrays i.e arr and arr2
for(int a=0;a<arr.length;a++){
for(int b=0;b<arr2.length;b++){
if(arr[a]==arr2[b]){
break;
}
else{
System.out.println("missing element is : "+arr[a]);
}
}
}
}
}
I want the number which is missing. Can anyone please let me know where I went wrong?
Check below code for if input array is any order or shuffled maner
public class MissingNumber {
public static void main(String[] args) {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 9, 9, 10};
System.out.println(arr.length);
int arr2[] = new int[10];
for (int i = 0; i < arr2.length; i++) {
arr2[i] = i + 1;
}
for (int a = 0; a < arr2.length; a++) {
int count = 0;
for (int b = 0; b < arr.length; b++) {
if (arr2[a] == arr[b]) {
break;
} else {
count++;
}
}
if (arr2.length == count) {
System.out.println("missing element is : " + arr2[a]);
}
}
}
}
You are breaking out from the loop once there is a match from the 2 arrays. From the point of your logic, change it to (you don't need nested loops):
if(arr[a]!=arr2[a]){
System.out.println("missing element is : "+arr[a]);
break;
}
But if it is certain that the array is always in sequential order from 1 onwards, you don't need another array. Just do it as:
for(int x=0; x<arr.lengthl x++){
if(arr[x] != (x+1)){
System.out.println("Missing element is " + (x+1));
break;
}
}
Remove the second array, you don't need it and it might just lead to errors once you add elements to the original array.
Basically, replace your test by:
if(arr[a] != (a+1)){ System.out.println("Missing element: " + (a+1)); }
Don't break out of it, since there might be more elements missing.
You just broke the code when u found a correct match:
Just use the following:
if(arr[a] != arr2[b]){
System.out.println("missing element is : "+arr[a]);
break;
}
Or just replace break with continue
It is not working because you are looping through arr looking for any value that is not in arr2, and every element in arr IS in arr2. You want arr2 as the outer loop.
My program is : In an array 1-10 numbers are stored, one number is missing how do you find it?
It can also be done using just the array itself. Please note that it only works if one of the numbers is missing as specified in this question.
For Example,
Let Array be array = {1,2,3,4,5,6,7,9,9,10}.
Now, let us assume that Array will not always be sorted and hence the first step is to sort the array.
Arrays.sort(array);
Next step is to simply check the array's value at any given location, if the value != location + 1 then that is the missing number.
for(int x = 0; x < array.length; x++) {
if(array[x] != x + 1) {
System.out.println("Missing Entry: " + (x+1));
break;
}
}

Substitution in an Array List

I have to list out 10 unique numbers between 1 and 20, but before storing the numbers, the program should check whether the number is in the list or not. If the number is already in the list, it should generate a new number. Also, the amount of numbers replaced must be counted.
This is what I have so far:
public static void main(String[] args)
{
int[] arrayA = {16, 14, 20, 3, 6, 3, 9, 1, 11, 2};
System.out.print("List: ");
for(int w = 0; w < arrayA.length; w++)
{
System.out.print(arrayA[w] + " ");
}
}
As you can see, there are two "3"s on the list, I have to output the same list but change one of the "3"s. Plus it has to be counted.
This is not hard to do, but what do you mean by change one of the threes?
You can add a boolean flag outside of your for loop that can tell if you've encountered a 3 or not and what the index of that 3 is.
Try something like this:
boolean changedThree = false;
int threeIndex = -1;
for(int i = 0; i < arrayA.length; i++){
if(arrayA[i] == 3 && !changedThree){
arrayA[i] = 4;
threeIndex = i;
changedThree = true;
}
System.out.println(arrayA[i] + " ");
}
I don't know for sure if that captures the information you need, but hopefully can give you a push in the right direction. Let me know if you have questions.
EDIT
To avoid any duplicate values, I recommend you create an array list, and add the unique values to it. Then, you can use the ArrayList.contains() method to see if a value exists already. So, I would recommend changing your code to this:
ArrayList<int> usedCharacters = new ArrayList<int>();
int changedCounter = 0;
Random rand = new Random();
for(int i = 0; i < arrayA.length; i++){
if(!usedCharacters.contains(arrayA[i])){ // If we haven't used this number yet
usedCharacters.add(arrayA[i]);
} else{
// Generate a new number - make sure we aren't creating a duplicate
int temp = rand.nextInt(20) + 1;
while(usedCharacters.contains(temp)){
temp = rand.nextInt(20) + 1;
}
// Assign new variable, increment counter
arrayA[i] = temp;
changedCounter++;
}
}
If you're not familiar with the random.nextInt() method, read this.
so if I understand you correctly you have to save the arrayA, right?
If that is the case, you can just make a new array, targetArray where you can save to numbers to, and then check using a for-loop if you already added it, and if so you can generate a new, random number.
The result would look something like this:
public static void main(String[] args) {
int[] arrayA = {16, 14, 20, 3, 6, 3, 9, 1, 11, 2};
int[] targetArray = new int[10];
int numbersReplaced = 0;
System.out.print("List: ");
for (int i = 0; i < arrayA.length; i++) {
for (int j = 0; j < targetArray.length; j++) {
if (arrayA[i] == targetArray[j]) {
targetArray[j] = (int)(Math.random() * 100);
numbersReplaced++;
} else {
targetArray[j] = arrayA[i];
}
}
}
System.out.println("Numbers replaced: " + numbersReplaced);
}
Hope that helped
You could use recursion to achieve your result.
This will keep looping until all values are unique
private void removeDoubles(int[] arr) {
for(int i = 0; i < arr.length; i++)
{
// iterate over the same list
for(int j = 0; j < arr.length; j++) {
// Now if both indexes are different, but the values are the same, you generate a new random and repeat the process
if(j != i && arr[i] == arr[j]) {
// Generate new random
arr[j] = random.nextInt(20);
// Repeat
removeDoubles(arr);
}
}
}
}
Note: This is the sort of question I prefer to give guidance answers rather than just paste in code.
You could walk the array backward looking at the preceding sublist. If it contain the current number you replace with a new one.
Get the sublist with something like Arrays.asList(array).subList(0, i) and then use .contains().
You logic for finding what number to add depends on lots of stuff, but at it simplest, you might need to walk the array once first to find the "available" numbers--and store them in a new list. Pull a new number from that list each time you need to replace.
EDIT: As suggested in the comments you can make use of Java Set here as well. See the Set docs.

Finding out the frequency of unique numbers

I am trying to solve a problem in Java as part of my assignment. The problem is as below:
The user enters ten numbers one by one upon prompting by the screen. The screen then assigns all the distinct value to an array and a similar array to hold the frequency of how many times those numbers have appeared.
I have done the below work, but seems I am stuck somewhere in assigning the frequencies and distinct values to the arrays:
import java.util.*;
public class JavaApplication10
{
public static void main(String[] args)
{
int [] numbers = new int [10];
int [] count = new int[10];
int [] distinct = new int[10];
for (int k=0;k<10;k++)
{
count[k]=0;
distinct[k]=0;
}
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter number 0: ");
numbers[0]=input.nextInt();
count[0]=1;
distinct[0]=numbers[0];
int j=0;
for (int i = 1;i<10;i++)
{
System.out.print("Enter number "+i+": ");
numbers[i]=input.nextInt();
while(j<i)
{
if (distinct[j]==numbers[i])
count[j]=count[j]+1;
else
distinct[j+1]=numbers[i];
j++;
}
}
for (int k=0;k<10;k++)
{
System.out.println(distinct[k]+ " "+count[k]);
}
}
}
I know that it is not fair to ask someone to help me solve the problem. But any kind of hint will be helpful.
Thank you
are the numbers limited to 0-9? If so, I would simple do the assignment.
(please note you will assign the input to a variable called "input"):
numbers[0]=input;
count[input]++;
Also you can start your for loop in "0" to avoid the assignment prior to the for loop.
Just a hint.
Hope this helps!
the ideal data structure would be a HashMap
Steps:
1) initialize an array to store the numbers and for each input
2) check if a hashmap entry with key as the entered number already exists
3) if exists simply increase its count
4) else create new entry with key as the number and count as 1
so at the end your frequencies would be calculated
if you are forced to use 2 arrays
1) initialize two arrays
2) for each input loop the number array and check whether that number is already in the array
3) if so take the array index and increment the value of the frequency array with the same index
4) if not freq[index] = 1
A proper way of doing that would be:
public Map<Integer, Integer> getFrequencies(Iterable<Integer> numbers) {
Map<Integer, Integer> frequencies = new HashMap<Integer, Integer>();
for(Integer number : numbers) {
if (frequencies.get(number) == null) {
frequencies.put(number, 0);
}
frequencies.put(number, frequencies.get(number) + 1);
}
return frequencies;
}
It returns a map number -> frequency.
Arrays are not a way to go in Java, they should be avoided whenever possible. See Effective Java, Item 25: Prefer lists to arrays.
I removed the Scanner object to write the code faster, just replace it with your code above and it should work.
int[] numbers = { 1, 2, 2, 2, 3, 3, 3, 1, 1, 2 };
int[] count = new int[10];
int[] distinct = new int[10];
count[0] = 1;
distinct[0] = numbers[0];
int disPos = 1; //Current possition in the distinct array
boolean valueInarray = false;
for (int i = 1; i < 10; i++) {
valueInarray = false;
for (int d = 0; d < i; d++) {
if (numbers[i] == distinct[d]) {
count[d] = count[d] + 1;
valueInarray = true;
break;
}
}
if (!valueInarray) {
distinct[disPos] = numbers[i];
count[disPos] = 1;
disPos++;
}
}
If you ABSOLUTELY HAVE TO use arrays.. here is a way to do it…
import java.util.Scanner;
import java.util.Arrays;
public class JavaApplication10
{
public static void main(String[] args)
{
int [] numbers = new int [10];
int [] count = new int[10];
int [] distinct = new int[10];
int [] distinct1 = new int[1];
int distinctCount = 0;
boolean found = false;
Scanner input = new Scanner(System.in);
for (int i=0; i<10; i++) {
found = false;
System.out.print("Enter number " + i);
numbers[i]=input.nextInt(); //Add input to numbers array
for (int j=0; j<=distinctCount; j++)
{
if (distinct1[j] == numbers[i]){ // check to see if the number is already in the distinct array
count[j] = count[j] + 1; // Increase count by 1
found = true;
break;
}
}
if (!found) {
distinct[distinctCount] = numbers[i];
count[distinctCount] = 1;
distinctCount++;
distinct1 = Arrays.copyOf(distinct, distinctCount+1);
}
}
for (int j=0; j<distinctCount; j++)
System.out.println("The number " + distinct1[j] + " occurs " + count[j] + " times" );
}
}
I think this is what you need, correct me if I'm wrong...
import java.util.HashMap;
import java.util.Scanner;
public class JavaApplication10 {
public static void main(String[] args) {
// Initializing variables
int[] numbers = new int[10];
HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
Scanner input = new Scanner(System.in);
// Getting the 10 inputs
for(int x=0; x<10; x++) {
// Asking for input
System.out.println("Enter number "+x+":");
numbers[x]=input.nextInt();
// If the table contains the number, add 1
// Otherwise: set value to 1
if(table.containsKey(numbers[x]))
table.put(numbers[x], table.get(numbers[x])+1);
else
table.put(numbers[x],1);
}
// Closing the reader
input.close();
// Get the highest and smallest number
int highest=0;
int smallest=0;
for(int i:table.keySet()) {
if(i>highest)
highest=i;
if(i<smallest)
smallest=i;
}
// For every value between the smallest and the highest
for (int x=smallest; x<=highest; x++) {
// Check if the frequency > 0, else continue
if(table.get(x)==null)
continue;
// Output
System.out.println(x+" is "+table.get(x)+" times in \'frequence\'");
}
}
}
This also handles with negative numbers, unlike the other's codes. If you don't want to use HashMaps let me know so I can create something with arrays.
Let me know if it (doesn't) works!
Happy coding (and good luck with your assignment) ;) -Charlie

Categories

Resources