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()?
Related
Memoization is giving me wrong answers. Please can some one help me out here. Without memorization, I am getting the right answers as in function targetBestR, but in the memoized function targetBestM, I am getting the wrong values being stored in the array list for the respective keys.
import java.util.ArrayList;
import java.util.HashMap;
public class TargetSumBest {
public static ArrayList<Integer> targetBestR(int n, int arr[]){
if(n==0) return new ArrayList<Integer>();
if(n<0) return null;
ArrayList<Integer> shortestCombo=null;
for(int i=0;i<arr.length;i++) {
//System.out.println(i);
//System.out.println(arr[i]);
int rem=n-arr[i];
//System.out.println(n+"-"+i+"="+rem);
ArrayList<Integer> tar=targetBestR(rem, arr);
if(tar!=null) {
tar.add(arr[i]);
if(shortestCombo==null||tar.size()<shortestCombo.size()) {
shortestCombo=tar;
}
}
}
//System.out.println(n+"value"+shortestCombo);
return shortestCombo;
}
public static ArrayList<Integer> targetBestM(int n, int arr[], HashMap<Integer, ArrayList<Integer>> memo){
if(n==0) return new ArrayList<Integer>();
if(n<0) return null;
if(memo.containsKey(n)) return memo.get(n);
ArrayList<Integer> shortestCombo=null;
for(int i=0;i<arr.length;i++) {
//System.out.println(i);
//System.out.println(arr[i]);
int rem=n-arr[i];
//System.out.println(n+"-"+i+"="+rem);
ArrayList<Integer> tar=targetBestM(rem, arr,memo);
if(tar!=null) {
tar.add(arr[i]);
if(shortestCombo==null||tar.size()<shortestCombo.size()) {
shortestCombo=tar;
}
}
}
//System.out.println(n+"value"+shortestCombo);
memo.put(n, shortestCombo);
return shortestCombo;
}
public static void main(String[] args) {
int n=8; int arr[]= {1,4,2};
System.out.println(targetBestM(n, arr, new HashMap<Integer, ArrayList<Integer>>()));
System.out.println(targetBestR(n, arr));
}
}//error
Was able to find the problem. The array passed into the HashMap keeps getting used and added to. Was able to fix it by creating new ArrayLists when reading and writing from the HashMap.
when reading...
if (memo.containsKey(n)) {
System.out.println(indent + n + " memo.get(n) = " + memo.get(n));
return new ArrayList<>(memo.get(n));
}
when writing...
memo.put(n, new ArrayList<>(shortestCombo));
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
I'm a beginner in Java, I need to do this exercise for school:
Write a method that gets an array of numbers and returns an array with the index of the minimum and maximum values inside the array.
Example: for int[] arr = {70,16,-3,5,90}, the method will return {2,4}
My code is this:
public class MinAndMax {
public static int main (String[] args) {
int[] myArray = {2,7,32,89,32,1,56,73,99,3827,56};
int min = myArray[0];
int max = myArray[0];
for (int i=0; i<myArray.length; i++) {
if (myArray[i]<min) {
min = myArray[i];
}
else if (myArray[i]>max) {
max = myArray[i];
}
}
int[] result = new int[2];
result[0] = min;
result[1] = max;
return result;
}
}
I don't understand the error message, I know I can't transform an int into an int[], but I created a new int[] here, so I don't see the error.
You should not return result array like that. Because you are writing that inside the void main function.
you code should do something like below,
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class MinAndMax
{
public static void main (String[] args) throws java.lang.Exception
{
int[] myArray = {2,7,32,89,32,1,56,73,99,3827,56};
int min = myArray[0];
int max = myArray[0];
for (int i=0; i<myArray.length; i++) {
if (myArray[i]<min) {
min = myArray[i];
}
else if (myArray[i]>max) {
max = myArray[i];
}
}
int[] result = new int[2];
result[0] = min;
result[1] = max;
System.out.println(Arrays.toString(result));
}
}
You get the error incompatible types: int[] cannot be converted to int because the main method has a int return type but you return int[].
To resolve the problem, use the standard main method signature public static void main (String[] args) since this allows the compiler to run the main method when you run the .java file.
To print the min and max values, you could extract the logic for finding min and max values to a separate method (e.g., getMinAndMaxValueIndices) and call it from the main method:
import java.util.Arrays;
class Main {
public static void main (String[] args) {
int[] minAndMaxValues = getMinAndMaxValues();
// print individual elements
int min = minAndMaxValues[0];
int max = minAndMaxValues[1];
System.out.println("min="+min+"\n"); // prints min=1
System.out.println("max="+max+"\n"); // prints max=3827
// print the array
System.out.println(Arrays.toString(minAndMaxValues)); // prints [1, 3827]
}
private static int[] getMinAndMaxValues() {
int[] myArray = {2,7,32,89,32,1,56,73,99,3827,56};
int min = myArray[0];
int max = myArray[0];
for (int i=0; i<myArray.length; i++) {
if (myArray[i]<min) {
min = myArray[i];
}
else if (myArray[i]>max) {
max = myArray[i];
}
}
int[] result = new int[2];
result[0] = min;
result[1] = max;
return result;
}
}
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 7 years ago.
So I'm trying to make a set of methods that find the mode of a set of ints given to it (in the form of an array), and return an array holding all of the modes, including the possibility of no modes. I sat down for a while writing these snippets of code and I couldn't get it to work, after extensive debugging. The code isn't in great style but I just want to know if anyone could figure out what is going wrong. By the way, the main() method is just there to test out the method. Here's the code:
public static int[] getMode(int[] numset) {
Map<Integer, Integer> vals = new HashMap<Integer, Integer>();
ArrayList<Integer> modes = new ArrayList<Integer>();
int highCount = 0;
for(int num : numset) {
if(vals.containsKey(num))
vals.put(num, vals.get(num) + 1);
else
vals.put(num, 0);
}
if(allValuesEqual(vals)) return new int[0];
for(int key : vals.keySet()) {
if(vals.get(key) > highCount) {
highCount = vals.get(key);
}
}
for(int key : vals.keySet()) {
if(vals.get(key) == highCount)
modes.add(key);
}
int[] mode = new int[modes.size()];
int count = 0;
for(int num : modes) {
mode[count] = num;
count++;
}
return mode;
}
private static boolean allValuesEqual(Map<Integer,Integer> vmap) {
ArrayList<Integer> a = new ArrayList<Integer>();
for(int key : vmap.keySet()) {
a.add(vmap.get(key));
}
for(int i = 0, n = a.size(); i < n; i++) {
if(a.get(i) != a.get(0) && i != 0)
return false;
}
return true;
}
public static void main(String[] args) {
int[] array = {6,10,10};
System.out.println(getMode(array));
}
The result: [I#677327b6.
I am utterly stumped. Any ideas?
You can use Arrays.toString() to easily print out the contents of your array:
public static void main(String[] args) {
int[] array = {6,10,10};
System.out.println(Arrays.toString(getMode(array)));
}
The previous result you were getting [I#677327b6 was a reference value.
I am trying to add random numbers to an empty array 20 numbers 0-99. When I run the code below it prints out 51 numbers and they are all 0.
Can someone please help me figure out what I am doing wrong here.
import java.util.Random;
public class SortedArray
{
int randomValues;
int[] value;
public SortedArray()
{
}
public int getRandom()
{
Random random = new Random();
for(int j=0; j<20; j++)
{
randomValues = random.nextInt(100);
}
return randomValues;
}
public int getArray()
{
int result = 0;
value = new int[randomValues];
for(int item : value)
{
System.out.println("The array contains " + item);
}
return result;
}
}
Here is my main method
public class ReturnSortedArray
{
public static void main(String[] args)
{
SortedArray newArray = new SortedArray();
int random = newArray.getRandom();
int array = newArray.getArray();
System.out.println(array);
}
}
In your method getArray
the code
value = new int[randomValues];
is simply creating a new empty int array of size ramdomValues.
As the default value of an int is 0, that is what you are getting
Also in your method getRandom you are setting the same value time and time again
for (...)
randomValues = random.nextInt(100);
try
public int[] getRandomArr()
{
int randomValues [] = new int [20];
Random random = new Random();
for(int j=0; j<20; j++)
{
randomValues[j] = random.nextInt(100);
}
return randomValues;
}
I see a few issues, you should probably set the values in your constructor. You could also call it a set method (since it's not actually a get). Also, your getArray() doesn't return an array. So, I think you really wanted something like this,
public class SortedArray {
private Random random = new Random();
private int[] value = new int[20];
public SortedArray() {
super();
setRandomValues();
}
public void setRandomValues() {
for (int j = 0; j < value.length; j++) {
value[j] = random.nextInt(100);
}
}
public int[] getArray() {
return value;
}
}
And then your main method, should be updated like
public static void main(String[] args) {
SortedArray newArray = new SortedArray();
int[] array = newArray.getArray();
System.out.println(Arrays.toString(array));
}