When I try to concatenate elements from a int[] that is a member of a class into a String, it works fine. But when I do the same procedure with a temp int[] (generated from Arrays.copyOf), I get jibberish. I don't understand why this is happening. A boiled down version of my code goes like this:
import java.util.*;
import java.io.*;
public class Test {
public int[] arr;
public Test(int[] arr) {
this.arr = arr;
}
public void fn() {
// ...
int[] temp = Arrays.copyOf(arr, arr.length);
System.out.println(this);
System.out.println(temp);
}
/*
* Takes an integer array as input and returns a string representation
* of the elements in the array.
*/
public String arrayToString(int[] arr) {
String s = "[";
int i = 0;
while(i < (arr.length - 1)) {
s = s + arr[i++] + ", ";
}
s = s + arr[i] + "]";
return s;
}
public String toString() {
return arrayToString(this.arr);
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
Test test = new Test(arr);
test.fn();
/*
* Produces result:
* [1, 2, 3, 4]
* [I#3343c8b3
*/
}
}
Why does this happen? As far as I can tell, both arr and temp should be of type int[].
Your local copy is going via arrayToString() because you println(this) which invokes toString().
Your temp copy is just trying to dump the int[] - try using arrayToString(temp) instead of println(temp).
This is unnecessary:
public String toString() {
return arrayToString(this.arr);
}
but you could replace it with:
public String toString() {
return Arrays.toString(this.arr);
}
Related
I'm trying to implement a java code to test linear search on a sorted array and this is my code
public class ArrayTest {
public static void main(String [] args) {
int []x= {12,8,6,23,6,5,17,20,9};
int y =linearSearch(x,23);
}
public static int linearSearch(int []ar,int value) {
int searchedIndex=-1;
for(int i=0;i<ar.length;i++) {
if (ar[i]==value) {
searchedIndex=i;
break;
}
}
return searchedIndex ;
}
}
The problem is that this doesn't generate any output also no errors were generated. Can anyone explain the reason for this.
In order to print something to the output,you must use System.out.println() function.The answer is returned to the variable y.Just print the variable to the console output.Moreover,the array is not sorted.But,that doesn't make any problem to it.
Something like this:
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args) {
int[] x = {12, 8, 6, 23, 6, 5, 17, 20, 9};
// Arrays.sort(x);
int y = linearSearch(x, 23);
System.out.println("" + y);
// int z = Arrays.binarySearch(x, 23);
// System.out.println("" + z);
}
public static int linearSearch(int[] ar, int value) {
for (int i = 0; i < ar.length; i++) {
if (ar[i] == value) {
return i;
}
}
return -1;
}
}
Note the commented out lines are for if you actually wanted a sorted array instead of an unsorted array
Here's the main method:
package main;
import varArgs.VarArgs;
public class Main {
public static void main(String[] args) {
int answer;
answer = VarArgs.sum(new int[]{1,2,3});
System.out.println("sum of ints = " + answer);
answer = VarArgs.sum(new int[]{1,2,3}, new int[] {100, 200, 300});
System.out.println("sum of ints = " + answer);
}
}
Here's the var args method:
package varArgs;
public class VarArgs {
/***
* Add an array of integers
* #param numbers Some array of integers
* #return The sum of all the elements in num
*/
public static int sum(int... numbers) {
int result = 0;
for (int i : numbers) {
result += i;
}
return result;
}
}
Here's the error I get:
A varargs parameter can only accept a single array. If you want to pass in a variable number of arrays, you need to do this:
public static int sum(int[]... arrays) {
int sum = 0;
for (int[] numbers : arrays) {
for (int i : numbers) {
sum += i;
}
}
return sum;
}
How can I write a test to print this result?
package leetcode_one_twenty;
import java.util.HashMap; // HashMap package
public class Two_Sum {
public int[] twoSum(int[] numbers, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < numbers.length; i++) {
if (map.get(numbers[i]) != null) {
int[] result = {map.get(numbers[i]) + 1, i + 1};
return result;
}
map.put(target - numbers[i], i);
}
int[] result = {};
return result;
}
public static void main(String[] args) {
// How can I write a test to print this result? THX!
}
}
Make your twoSum method static, and call it with values from your main method:
int[] myArray = {1,2,3};
int target = 5;
System.out.println(Arrays.toString(twoSum(myArray, target)));
I'm not really sure what are you exactly trying to do. Why not try System.out.println() and toString()?
Okay I am a pretty beginner java coder, and I am doing an assignment where I am stuck. I need to create a generic method (sort) that sorts a Type array according to frequency, basically, I am taking the CountingSort Algorithm and making it a generic method. This is where I am lost. I can't seem to figure out how to do this.
Here is a link to my instructions,
https://classes.cs.siue.edu/pluginfile.php/7068/mod_assign/intro/150mp08.pdf
Code:
Driver Class
package mp08;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Lists array = new Lists();
array.populateLists();
System.out.println("Original Int List: \n");
array.sort(Lists.intList);
System.out.println("Sorted Int List: \n");
}
}
Lists Class
package mp08;
import java.util.Arrays;
import java.util.Random;
public class Lists {
public static Integer[] intList;
public static Integer[] sortedintList;
public static Integer[] frequency;
public static Character[] charList;
public static Character[] sortedcharList;
public static int MAX_SIZE = 101;
public static int lengthInt;
public static int lengthChar;
public Lists(){
this.intList = new Integer[MAX_SIZE];
this.sortedintList = new Integer[MAX_SIZE];
this.charList = new Character[MAX_SIZE];
this.sortedcharList = new Character[MAX_SIZE];
this.frequency = new Integer[MAX_SIZE];
this.lengthInt = 0;
this.lengthChar = 0;
}
//Makes random integer for populated lists method.
public int randomInt(int min, int max){
Random rand = new Random();
int randomNum = rand.nextInt((max-min)+1)+min;
return randomNum;
}
//Makes random character for populated lists method.
public char randomChar(){
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int N = alphabet.length();
Random rand = new Random();
char randomLet = alphabet.charAt(rand.nextInt(N));
return randomLet;
}
//Populates intList and charList with random values.
public void populateLists(){
for (int i = 0; i < MAX_SIZE; i++) {
intList[i] = randomInt(1,100);
lengthInt++;
}
for (int i = 0; i < MAX_SIZE; i++) {
charList[i] = randomChar();
lengthChar++;
}
}
//Returns sorted array
public Integer[] sorted(){
return intList;
}
public static <T> void sort(T[] array) {
// array to be sorted in, this array is necessary
// when we sort object datatypes, if we don't,
// we can sort directly into the input array
Integer[] aux = new Integer[array.length];
// find the smallest and the largest value
int min = 1;
int max = 101;
// init array of frequencies
int[] counts = new int[max - min + 1];
// init the frequencies
for (int i = 0; i < array.length; i++) {
counts[array[i] - min]++;
}
// recalculate the array - create the array of occurence
counts[0]--;
for (int i = 1; i < counts.length; i++) {
counts[i] = counts[i] + counts[i-1];
}
/*
Sort the array right to the left
1) Look up in the array of occurences the last occurence of the given value
2) Place it into the sorted array
3) Decrement the index of the last occurence of the given value
4) Continue with the previous value of the input array (goto set1),
terminate if all values were already sorted
*/
for (int i = array.length - 1; i >= 0; i--) {
aux[counts[array[i] - min]--] = array[i];
}
}
public static void main(String[] args) {
Integer [] unsorted = {5,3,0,2,4,1,0,5,2,3,1,4};
System.out.println("Before: " + Arrays.toString(unsorted));
Integer [] sorted = sort(unsorted);
System.out.println("After: " + Arrays.toString(sorted));
}
}
I obviously have not finished my driver class yet and I would appreciate any help I can get!
There's no generic way for any Comparable type to get its ordinal number. Sometimes such numbers do not exist at all (for example, String is Comparable, but you cannot map any String to the integer number). I can propose two solutions.
First one is to store counts not in the array, but in TreeMap instead creating new entries on demand (using Java-8 syntax for brevity):
public static <T extends Comparable<T>> void sort(T[] array) {
Map<T, Integer> counts = new TreeMap<>();
for(T t : array) {
counts.merge(t, 1, Integer::sum);
}
int i=0;
for(Map.Entry<T, Integer> entry : counts.entrySet()) {
for(int j=0; j<entry.getValue(); j++)
array[i++] = entry.getKey();
}
}
public static void main(String[] args) {
Integer[] data = { 5, 3, 0, 2, 4, 1, 0, 5, 2, 3, 1, 4 };
System.out.println("Before: " + Arrays.toString(data));
sort(data);
System.out.println("After: " + Arrays.toString(data));
Character[] chars = { 'A', 'Z', 'B', 'D', 'F' };
System.out.println("Before: " + Arrays.toString(chars));
sort(chars);
System.out.println("After: " + Arrays.toString(chars));
}
Such solution looks clean, but probably not very optimal (though its advantage is that it does not care whether all numbers are from 1 to 100 or not).
Another possible solution is to create some additional interface which defines ordering for given type:
public interface Ordering<T> {
int toOrdinal(T obj);
T toObject(int ordinal);
}
public class IntegerOrdering implements Ordering<Integer> {
#Override
public int toOrdinal(Integer obj) {
return obj;
}
#Override
public Integer toObject(int ordinal) {
return ordinal;
}
}
public class CharacterOrdering implements Ordering<Character> {
#Override
public int toOrdinal(Character obj) {
return obj;
}
#Override
public Character toObject(int ordinal) {
return (char)ordinal;
}
}
Now you may make your sort method accepting the ordering parameter:
public static <T> void sort(T[] array, Ordering<T> ordering) { ... }
Every time you need to get counts array index by T object, just call ordering.toOrdinal(object). Every time you need to get object by array index, just use ordering.toObject(index). So, for example, instead of
counts[array[i] - min]++;
Use
counts[ordering.toOrdinal(array[i]) - min]++;
And call the sorting method like this:
sort(characterArray, new CharacterOrdering());
sort(integerArray, new IntegerOrdering());
Hey I'm trying to write a method that compares two arrays and returns the number of values they have in common.
For example, if there are two arrays:
arr{0,4,2,5}
arr1{0,7,4,4}
Then the method would return 2.
This is what I have so far:
public int numDigitsCorrect(Permutation other) {
int c=0;
for(int i=0; i<nums.length; i++) {
for(int x=0; x<nums.length;x++) {
if(nums[i]==other.nums[x]) {
System.out.println(nums[i] + " " + other.nums[x] + " ");
c++;
}
}
}
return c;
}
You need to change in current function as mention below :
public int numDigitsCorrect(Permutation other)
{
int c=0;
for(int i=0; i<nums.length; i++) {
for(int x=0; x<other.length;x++) {
if(nums[i]==other[x]) {
System.out.println(nums[i] + " " + other[x] + " ");
c++;
}
}
}
return c;
}
I assume that nums and other are your int arrays as shown below
int[] nums = {0,4,2,5};
int[] other = {0,7,4,4};
If you use Set, it will be much more cleaner and readable. Also this will reduce the complexity of your code.
Like:
import java.util.HashSet;
import java.util.Set;
public class NumberMatch {
public static void main(String[] args) {
int[] arrOne = { 0, 4, 2, 5 };
int[] arrTwo = { 0, 7, 4, 4 };
System.out.println(numDigitsCorrect(arrOne, arrTwo));
System.out.println(numDigitsCorrect(arrTwo, arrOne));
System.out.println(numDigitsCorrect(arrOne, arrOne));
System.out.println(numDigitsCorrect(arrTwo, arrTwo));
}
public static int numDigitsCorrect(int[] arrOne, int[] arrTwo) {
Set<Integer> setOne = arrayToSet(arrOne);
Set<Integer> setTwo = arrayToSet(arrTwo);
setOne.retainAll(setTwo);
return setOne.size();
}
private static Set<Integer> arrayToSet(int[] array) {
Set<Integer> retSet = new HashSet<Integer>();
for (int i : array) {
retSet.add(i);
}
return retSet;
}
}
Output:
2
2
4
3