JAVA: What am I doing wrong? - java

I am trying to determine the Hamming distance between two arrays of ints. Pre: aList != null, bList != null, aList.length == bList.length; Post: return the Hamming Distance between the two arrays of ints. I am not sure what I am doing wrong, I am just now starting to learn how to code. Any help is appreciated. Thanks in advance :)
Here is my code:
public class test {
public static int hammingDistance(int[] aList, int[] bList) {
// check preconditions
if (aList == null || bList == null || aList.length != bList.length)
throw new IllegalArgumentException("Violation of precondition: " +
"hammingDistance. neither parameter may equal null, arrays" +
" must be equal length.");
//Starting a counter
int counter = 0;
System.out.println("test");
//checking to see if there is a mismatch in the values of the two given arrays
for (int i = 0; i < bList.length; i++) {
if (bList[i] != aList[i]) {
//increasing counter everytime there is a mismatch
counter++;
}
}
return counter;
}
public static void main(String[] args) {
int[] aList = { 1,3,3,4 };
int[] bList = { 1,2,10,4 };
System.out.println(hammingDistance(aList, bList));
}
}
Updated Code

You are resetting the counter to zero whenever there is a match. So counter in never effective. Remove the else part of the code.

You are resetting the counter when two elements are equal (see your else statement). You shouldn't be doing anything when two called are equal.
Hope it helps,

Related

How to print the index of an array into separate ArrayList

I have created a method for my program, where I compare two arrays, user and test. I am trying to add the index of the array user into the ArrayList qMissed when it is not the same as the test Array.
If both arrays are the exact same then it should just return null.
I am getting exception errors because I need to complete the reference type but I am unsure of what to do.
/**
* #param user
* #param test
* #return
*/
public static ArrayList<String> questionMissed(String[] user, String[] test)
{
ArrayList<int> qMissed = new ArrayList<int>();
for (int i = 0; i <= user.length-1; i++)
{
if (user[i] != test[i])
{
qMissed = Arrays.asList(qMissed).indexOf(user);(i+1);
}
else if (user[i] == test[i])
{
return null;
}
}
return qMissed;
}
Your method seems to have some logical and compilation issues.
Looks like you need this method,
public static List<Integer> questionMissed(String[] user, String[] test) {
List<Integer> qMissed = new ArrayList<Integer>();
for (int i = 0; i < user.length; i++) {
if (!user[i].equals(test[i])) {
qMissed.add(i);
}
}
return qMissed.size() == 0 ? null : qMissed;
}
Fixes and their explanation,
1. Your return type has to be List<Integer> instead of ArrayList<String> because you want to return an ArrayList of Integer indexes and not string.
2. Second problem you can't use primitive type in ArrayList<int> instead you need to use ArrayList<Integer>
3. You can't compare strings with == instead you need to use equals method on string.
4. You don't have to return null inside forloop else hence else block I have removed.
5. After you exit the forloop, as you want to return null if both element's arrays matched hence this code,
return qMissed.size() == 0 ? null : qMissed;
Let me know if you face any issues using this method.
Edit:
How to display "All are correct" message in case both passing arrays have same numbers. You must be calling it something like this,
List<Integer> list = questionMissed(user,test);
if (list == null) {
System.out.println("All are correct");
} else {
// your current code
}
You can try changing the return type from ArrayList to ArrayList in the method:
public static ArrayList<int> questionMissed(String[] user, String[] test) {
ArrayList<int> qMissed = new ArrayList<int>();
for (int i=0;i<=user.length-1;i++) {
if (user[i] != test[i]) {
qMissed = Arrays.asList(qMissed).indexOf(user);(i+1);
} else {
return null;
}
}
return qMissed;
}
Also you can remove the else if condition cause is redundant. Please attach the exceptionsyou are getting.
I see multiple issues with your code, Firstly as Andreas said ArrayList cannot host primitive types
so change it to
ArrayList<Integer> qMissed = new ArrayList<Integer>();
Second problem I see is that you are comparing Strings using == this compare can be wrong so use equals instead
(user[i].equals(test[i]))
and the last mistake I see is the code cannot be compiled, can you give me more information in the comments to what you are trying to do in this part since It's not valid code
qMissed = Arrays.asList(qMissed).indexOf(user);
(i + 1);
if you want to do something like Pushpesh Kumar Rajwanshi answer you can use java 8 streams what this does is makes an IntStream with the length of user, and then filters it to have only items if they don't equal at the same index and then adds it to qMissed.
public static List<Integer> questionMissed(String[] user, String[] test) {
List<Integer> qMissed = new ArrayList<>();
IntStream.range(0, user.length)
.filter(i -> !user[i].equals(test[i]))
.forEach(qMissed::add);
return qMissed.size() == 0 ? null : qMissed;
}
I guess you want like below ..
public static ArrayList<Integer> questionMissed(String[] user, String[]
test) {
ArrayList<Integer> qMissed = new ArrayList<Integer>();
int i = 0;
if(user.length == test.length ) {
while(i < user.length ){
if (!(user[i].equals(test[i]))) {
qMissed.add( i + 1);
}else {
return null;
}
i++;
}
if(user.length > 0 && i == user.length ) {
return qMissed;
}
}
return null;
}

Java BubbleSort

I am facing a problem where I need to sort a String array in alphabetical order. I am able to sort one array, but the problem starts when there are 2 more arrays, that correspond to the first array. Each value in each array should be in the same place, to make information not messed up. After sorting array1, it is in alphabetical order, but i don't have any idea how to make values from array2 and array3 change the positions the same like in array1 after sorting is finished.
My code so far is:
public void sort()
{
boolean finish = false;
while(finish == false){
finish = true;
for(int i=0;i<Country.length-1;i++)
{
int num = 0;
if(Country[i] != null && Country[i + 1] != null)
{
String name1=Country[i]; String name2=Country[i+1];
num=name1.compareTo(name2);
}
else if(Country[i] == null && Country[i + 1] == null){
num = 0;
}
else if(Country[i] == null){
num = 1;
}
else {
num = -1;
}
if(num>0)
{
String temp=Country[i];
Country[i]=Country[i+1];
Country[i+1]=temp;
finish=false;
}
}
}
By far the most recommended way is to re-design your program, and arrange all the related items in a single class. This is what objects are for, after all. Then you can make the object Comparable, give it a compareTo method, and sort it.
But if you are really unable to do that, what you should do is, whenever you exchange any two items in your sort array, make sure you exchange the corresponding items in the other arrays.
So, if you have arrays country, capital and headOfState, you will have to write something like:
String temp=country[i];
country[i]=country[i+1];
country[i+1]=temp;
temp=capital[i];
capital[i]=capital[i+1];
capital[i+1]=temp;
temp=headOfState[i];
headOfState[i]=headOfState[i+1];
headOfState[i+1]=temp;
This way, whenever you move anything in your main array, you'll also be moving the respective item in the other arrays, so they will stay together.
But again, it's much more preferred if you re-designed your program.
Also note the Java language conventions - variable names should not start with a capital letter, only type names should.
If you want all the array to be swaped based on the compare you did in the country array. You can just swap more than one array after one compare.
If(array1[i] > array1[i+1]){
Swap(array1[i],array1[i+1)
Swap(array2[i],array2[i+1])
}
By using a swap function, you can make it more simpler to do swaping in much more array.
You have to swap elements in Country and City arrays simultaneously.
public class BubbleSortTmp {
public String[] Country = {"z", "h", "a"};
public int[] City = {3, 2, 1};
public void printCountry() {
for (String s : Country) {
System.out.printf("%s ", s);
}
System.out.println();
}
public void printCity() {
for (int s : City) {
System.out.printf("%s ", s);
}
System.out.println();
}
public void sort() {
for (int outer = Country.length - 1; outer > 0; outer--) {
for (int inner = 0; inner < outer; inner++) {
if (Country[inner].compareTo(Country[inner+1]) > 0) {
swapCountry(inner, inner+1);
swapCity(inner, inner+1);
}
}
}
}
private void swapCountry(int first, int second) {
String tmp = Country[first];
Country[first] = Country[second];
Country[second] = tmp;
}
private void swapCity(int first, int second) {
int tmp = City[first];
City[first] = City[second];
City[second] = tmp;
}
public static void main(String[] args) {
BubbleSortTmp bs = new BubbleSortTmp();
System.out.println("Before: ");
bs.printCountry();
bs.printCity();
bs.sort();
System.out.println("After: ");
bs.printCountry();
bs.printCity();
}
}

Incorrect logic in my loop

public static void main(String[] args) {
Integer[] courses1 = {1,2,3};
Integer[] courses2 = {0,1};
Integer[] longestArr;
Integer[] shortestArr;
ArrayList commonCourses = new ArrayList();
if ( courses1.length > courses2.length)
{
longestArr = courses1; shortestArr = courses2;
}
else
{
longestArr = courses2; shortestArr = courses1;
}
for ( int i : longestArr)
{
for ( int j : shortestArr)
{
if (i == j);
commonCourses.add(i);
}
}
Collections.sort(commonCourses);
System.out.println(commonCourses.size());
}
No matter what the values of course1 and courses2, the arrayList commonCourses always has a size of one more the the total number of elements in both arrays when it is supposed to only contain the elements that are in both arrays. I have 2 questions why is ever element from the 2 arrays being added to the arrayList and why is the size of the arrayList always one more than the total number of elements? If you are wondering why I have courses1 and courses2 declared at the start, this is a problem from talentBuddy.co that I'm testing on eclipse. I have tested with different starting conditions and the same thing always happens.
My new slimmed down solution
public static void main(String[] args) {
Integer[] courses1 = {1};
Integer[] courses2 = {0};
ArrayList <Integer>commonCourses = new ArrayList<Integer>();
for ( int i : courses1)
{
for ( int j : courses2)
{
if (i == j)
commonCourses.add(i);
}
}
Collections.sort(commonCourses);
System.out.println(commonCourses.size());
}
Your problem is the semicolon in this line:
if (i == j);
The if clause ends here and the following line is always executed.
The semi-colon at the end of the if-condition is your problem. For a detailed explanation on why this happens, see this StackOverflow post. In short, the semi-colon causes the compiler to ignore the conditional at runtime.
for ( int j : shortestArr)
{
if (i == j);
// ^ Remove this semi-colon
commonCourses.add(i);
}
Using curly-braces to format your if-statements helps prevent this from happening:
if(condition){
doSomething();
}
for ( int j : shortestArr)
{
if (i == j);
// ^ REMOVE THIS SEMICOLON
commonCourses.add(i);
}
The problem is that extra semicolon. Your chunk of code is functionally identical to this right now:
for ( int j : shortestArr)
{
if (i == j)
{
}
commonCourses.add(i);
}
You have a misused semicolon after the if condition.
if (i == j);
I have never worked in a firm where they did not require parenthesis after if:
if (...) {
...
}
And the reason quite evident.
Let me show the most abstracted solution:
Courses are sets of unique course numbers
Common courses is an intersection set
In java one uses abstract interfaces like Set for the variable, but can implement that set with different implementing classes
One wants a sorted set, TreeSet is such an implementation
Set<Integer> courses1 = new HashSet<>();
Collections.addAll(courses1, 1, 2, 3);
SortedSet<Integer> courses2 = new HashSet<>();
Collections.addAll(courses2, 0, 1);
SortedSet<Integer> commonCourses = new TreeSet<>(courses1);
commonCourses.retainAll(courses2);

java.lang.ArrayIndexOutOfBoundsException: 4 Error

I'm new to coding and I've been writing this code and trying to make it work but every time I run it it crashes. I've looked things up and will writing this code I've followed java's website on how to properly write down code as well as this site.
Anyways, it would be greatly appreciated if someone can explain to me why this is not working because it seems to me like the logic is there but I don't get why it crashes.
My code:
import java.util.Scanner;
import java.lang.String;
import java.util.*;
public class Question1
{
public static void main(String[] args)
{
Scanner keyboard= new Scanner(System.in);
System.out.println("Enter either letters or numbers and I'll magically tell you if they are consecutive :D");
String inputedString= keyboard.nextLine();
boolean consecutiveOrNot=isConsecutive(inputedString);
System.out.println("Drum rolls...... Is it consecutive: "+ consecutiveOrNot); //Problem with this line?
}
public static boolean isConsecutive(String inputedString)
{
//Storing string's units into an array and converting to UpperCase if necessary
//and storing string's numerical value into the variable 'arrayCharToInt'
char[] charIntoArray= new char[inputedString.length()];
int[] arrayCharToInt= new int[inputedString.length()];
for (int i=0;i<inputedString.length();i++ )
{
charIntoArray[i]=inputedString.charAt(i);
if (Character.isLetter(charIntoArray[i]) && Character.isLowerCase(charIntoArray[i]))
{
charIntoArray[i]= Character.toUpperCase(charIntoArray[i]);
}
arrayCharToInt[i]=(int) charIntoArray[i];
}
// The next if statements and the methods that they call are used to verify
//that the content of the initial string is either letters or numbers, but not both together
boolean[] continuous= new boolean[arrayCharToInt.length];
boolean[] testContNumbersDecreasing= new boolean[arrayCharToInt.length];
boolean[] testContNumbersIncreasing= new boolean[arrayCharToInt.length];
boolean[] testContLettersDecreasing= new boolean[arrayCharToInt.length];
boolean[] testContLettersIncreasing= new boolean[arrayCharToInt.length];
Arrays.fill(continuous, true);
if (lowestValue(arrayCharToInt)>=65 && highestValue(arrayCharToInt)<= 90)
{
for (int x=0;x<arrayCharToInt.length ;x++ )
{
testContLettersIncreasing[x]=((arrayCharToInt[x+1]-arrayCharToInt[x]== 1) || (arrayCharToInt[x+1]-arrayCharToInt[x]== -25));
testContLettersDecreasing[x]=((arrayCharToInt[x]-arrayCharToInt[x+1]== 1) || (arrayCharToInt[x]-arrayCharToInt[x+1]== -25));
}
return (Arrays.equals(continuous,testContLettersIncreasing) || Arrays.equals(continuous,testContLettersDecreasing));
}
else if ((lowestValue(arrayCharToInt) >= 48) && (highestValue(arrayCharToInt)<= 57))
{
for (int x=0;x<arrayCharToInt.length ;x++ )
{
testContNumbersIncreasing[x]=((arrayCharToInt[x+1]-arrayCharToInt[x]== 1) || (arrayCharToInt[x+1]-arrayCharToInt[x]== -9));
testContNumbersDecreasing[x]=((arrayCharToInt[x]-arrayCharToInt[x+1]== 1) || (arrayCharToInt[x]-arrayCharToInt[x+1]== -9));
}
return (Arrays.equals(continuous,testContNumbersIncreasing) || Arrays.equals(continuous,testContNumbersDecreasing));
}
else
{
return false;
}
}
public static int lowestValue(int[] array)
{
int lowest=array[0];
for (int counter=0; counter< array.length; counter++)
{
if( lowest>array[counter])
lowest= array[counter];
}
return lowest;
}
public static int highestValue(int[] array)
{
int highest=array[0];
for (int counter=0; counter< array.length; counter++)
{
if( highest<array[counter])
highest= array[counter];
}
return highest;
}
}
The main method seems to be fine because it put everything in the isConsecutive method as a comment except for 'return true;' and indeed the program ran and printed true. So I know the problem lies somewhere in the second method.
If there's anything that I did not do right please tell me and that would be greatly appreciated. After all I'm still learning.
Thanks
All of your calls to arrayCharToInt[x+1] are going to go out of bounds on the last iteration of the loop they're in (for example, if arrayCharToInt.length equals 5, the highest that x is going to go is 4. But then x+1 equals 5, which is out of bounds for an array with five cells). You'll need to put in some sort of if( x == arrayCharToInt.length - 1) check.
in the method isConsecutive inside the for loop: for (int x=0;x<arrayCharToInt.length ;x++ ) , you have used arrayCharToInt[x+1]
if the arrayCharToInt lenth is 4 , then you have arrayCharToInt [0] to arrayCharToInt [3].
now consider this statement:arrayCharToInt[x+1]
when x is 3 this statement will evalueate to arrayCharToInt[4] resulting in array index out of bounds exception
This error throw when something went wrong in the Array calling function.
You got the length and make it print.
for eg:
int a[] = {1,2,3,4}
Length of this array is,
int length = a.length
So length = 4 but highest index is 3, not 4. That means index of the array started with 0. So you have to print:
arr[length-1];
In your program,
x == arrayCharToInt.length - 1

Is it possible to find out if a value exists twice in an arraylist?

I have an integer arraylist..
ArrayList <Integer> portList = new ArrayList();
I need to check if a specific integer has already been entered twice. Is this possible in Java?
You could use something like this to see how many times a specific value is there:
System.out.println(Collections.frequency(portList, 1));
// There can be whatever Integer, and I use 1, so you can understand
And to check if a specific value is there more than once you could use something like this:
if ( (Collections.frequency(portList, x)) > 1 ){
System.out.println(x + " is in portList more than once ");
}
My solution
public static boolean moreThanOnce(ArrayList<Integer> list, int searched)
{
int numCount = 0;
for (int thisNum : list) {
if (thisNum == searched)
numCount++;
}
return numCount > 1;
}
If you are looking to do this in one method, then no. However, you could do it in two steps if you need to simply find out if it exists at least more than once in the List. You could do
int first = list.indexOf(object)
int second = list.lastIndexOf(object)
// Don't forget to also check to see if either are -1, the value does not exist at all.
if (first == second) {
// No Duplicates of object appear in the list
} else {
// Duplicate exists
}
This will tell you if you have at least two same values in your ArrayList:
int first = portList.indexOf(someIntValue);
int last = portList.lastIndexOf(someIntValue);
if (first != -1 && first != last) {
// someIntValue exists more than once in the list (not sure how many times though)
}
If you really want to know how many duplicates of a given value you have, you need to iterate through the entire array. Something like this:
/**
* Will return a list of all indexes where the given value
* exists in the given array. The list will be empty if the
* given value does not exist at all.
*
* #param List<E> list
* #param E value
* #return List<Integer> a list of indexes in the list
*/
public <E> List<Integer> collectFrequency(List<E> list, E value) {
ArrayList<Integer> freqIndex = new ArrayList<Integer>();
E item;
for (int i=0, len=list.size(); i<len; i++) {
item = list.get(i);
if ((item == value) || (null != item && item.equals(value))) {
freqIndex.add(i);
}
}
return freqIndex;
}
if (!collectFrequency(portList, someIntValue).size() > 1) {
// Duplicate value
}
Or using the already availble method:
if (Collections.frequency(portList, someIntValue) > 1) {
// Duplicate value
}
Set portSet = new HashSet<Integer>();
portSet.addAll(portList);
boolean listContainsDuplicates = portSet.size() != portList.size();
I used the following solution to find out whether an ArrayList contains a number more than once. This solution comes very close to the one listed by user3690146, but it does not use a helper variable at all. After running it, you get "The number is listed more than once" as a return message.
public class Application {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(4);
list.add(8);
list.add(1);
list.add(8);
int number = 8;
if (NumberMoreThenOnceInArray(list, number)) {
System.out.println("The number is listed more than once");
} else {
System.out.println("The number is not listed more than once");
}
}
public static boolean NumberMoreThenOnceInArray(ArrayList<Integer> list, int whichNumber) {
int numberCounter = 0;
for (int number : list) {
if (number == whichNumber) {
numberCounter++;
}
}
if (numberCounter > 1) {
return true;
}
return false;
}
}
Here is my solution (in Kotlin):
// getItemsMoreThan(list, 2) -> [4.45, 333.45, 1.1, 4.45, 333.45, 2.05, 4.45, 333.45, 2.05, 4.45] -> {4.45=4, 333.45=3}
// getItemsMoreThan(list, 1)-> [4.45, 333.45, 1.1, 4.45, 333.45, 2.05, 4.45, 333.45, 2.05, 4.45] -> {4.45=4, 333.45=3, 2.05=2}
fun getItemsMoreThan(list: List<Any>, moreThan: Int): Map<Any, Int> {
val mapNumbersByElement: Map<Any, Int> = getHowOftenItemsInList(list)
val findItem = mapNumbersByElement.filter { it.value > moreThan }
return findItem
}
// Return(map) how often an items is list.
// E.g.: [16.44, 200.00, 200.00, 33.33, 200.00, 0.00] -> {16.44=1, 200.00=3, 33.33=1, 0.00=1}
fun getHowOftenItemsInList(list: List<Any>): Map<Any, Int> {
val mapNumbersByItem = list.groupingBy { it }.eachCount()
return mapNumbersByItem
}
By looking at the question, we need to find out whether a value exists twice in an ArrayList. So I believe that we can reduce the overhead of "going through the entire list just to check whether the value only exists twice" by doing the simple check below.
public boolean moreThanOneMatch(int number, ArrayList<Integer> list) {
int count = 0;
for (int num : list) {
if (num == number) {
count ++ ;
if (count == 2) {
return true;
}
}
}
return false;
}

Categories