public static void main(String[] args) {
int[] HwArray = new int[10];
for (int i = 0; i < HwArray.length; i++) {
HwArray[i] = i;
}
int count = 0;
for (int i = 0; i < HwArray.length; i++){
HwArray[i] = (int) (100 + Math.random() * 100);
System.out.print("HwArray[i]=" + HwArray[i]);
}
}
{
int[] reverse(int[] HwArray); {
int[] reversed = new int[HwArray.length];
for (int i=0; i<HwArray.length; i++) {
reversed[i] = HwArray[HwArray.length - 1 - i];
}
return reverse;
}
}
}
Sorry, I'm still learning. I'm trying to reverse the order of all the elements, but I keep receiving an error. Am I doing something wrong?
To be honest, you're actually not that far off. The reverse function actually seems to work okay but you have all kinds of weird syntax errors and you're not even calling the reverse method. Try doing this:
Move the reverse method inside the class where main is defined. If you want to call it directly from main you'll have to make it an static method.
Get rid of the extra curly braces on lines 17 and 25.
Remove the semicolon on line 18 when declaring reverse. It shouldn't be there.
The reverse method is trying to return a variable called reverse. That's the name of the method, you can't do that. I think you meant to return reversed.
Actually call the reverse method after you have initialized the array with random numbers. Then print the array out again to verify that it worked.
Notice that you're not actually printing out the values of the array on line 11. That should be System.out.println("HwArray[" + i + "]=" + HwArray[i]);
I think the conceptually easiest way to reverse the order of elements in an array is to swap each ith element in the first half of the array of size N with the N-ith element in the second half:
int[] reversed = new int[10];
for (int i=0; i < HwArray.length/2; ++i) {
reversed[i] = HwArray[HwArray.length-1-i];
reversed[HwArray.length-1-i] = HwArray[i];
}
Demo here:
IDEOne
There are many errors:
First of all, it should be return reversed instead of return reverse.
Then, you cannot define any method inside a method(here, method reverse is defined inside the main method)
Then, you can do one thing, remove the following two braces:
1: The opening brace just before int[] reverse(int[] HwArray)
2: The closing brace in the last line
Last, it should be int[] reverse(int[] HwArray) { instead of int[] reverse(int[] HwArray); {
Comparator<Integer> comparator = new Comparator<Integer>() {
#Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
};
// option 1
Integer[] array = new Integer[] { 11, 44, 4, 3, 123 };
Arrays.sort(array, comparator);
// option 2
int[] array2 = new int[] {11, 44, 4, 3, 123};
List<Integer>list = Ints.asList(array2);
Collections.sort(list, comparator);
array2 = Ints.toArray(list);
// option 3
List<Integer> integersList = Ints.asList(arr);
Collections.sort(integersList, Collections.reverseOrder());
Related
I am trying to get pass a coding challenge. The goal is to remove duplicate (after a defined 'n-th' time) from the array.
For example,
int[] arr;
arr = new int[] {1, 2, 2, 3, 3, 3, 4, 5, 5};
arr = tester(arr,1);//return 1,4. anything having more then 1 occurrence is removed from the //array
I have 2 questions here.
I understand that although java is mainly call by value,
more detail: https://stackoverflow.com/questions/12757841/are-arrays-passed-by-value-or-passed-by-reference-in-java#:~:text=Longer%20answer%3A,object%20that%20the%20caller%20sees.
and
Is Java "pass-by-reference" or "pass-by-value"?
.
so am I not able to modify/return the value of arr without re-assigning it as I need to use the "new" keyword later on.
example:
I am not able to do the following:
tester(arr,1) //return the original value, as the method has a "new" when converting the
//arraylist into array. There seems to be no work around for this as well..
I am also only passing 2 out of 10 test case in the coding challenge, I am not very sure why. I have also attempted to error handle with string inputs, or length=0 or null, to no success. (or implemented it in hashmap for sake of time complexity)
It does not seem like my logic has an issue, I am just not sure what are the test case as it is hidden.
I believe part of the challenge requires me to return it in the original array, meaning changing the value of arr itself, but i cant find a way to do it without using the new keyword.
Any ideas anyone?
public static int[] tester(int[] data, int n)
{
ArrayList<Integer> storeNon_dup = new ArrayList<Integer>();
//nested for loop to run through the array
//store in arrayList if criteria valid
for(int i = 0; i < data.length; i++)
{
int counter = 0;
for(int j = 0; j< data.length; j++)
{
if(data[i] == data[j])
{
counter++;
}
}
//if not duplicate in n-th occurence, add to list
if(counter<=n)
{
storeNon_dup.add(data[i]);
}
}
//convert arraylist to array
int[] container = new int[storeNon_dup.size()];
for(int i = 0; i<storeNon_dup.size(); i++)
{
container[i] = storeNon_dup.get(i);
}
return container;
}
Alternate solution by using HashMap.
public static List tester(int[] data, int n) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0; i<data.length; i++) {
if(map.containsKey(data[i])) {
map.put(data[i], map.get(data[i])+1);
}else {
map.put(data[i], 1);
}
}
List lst = new ArrayList<Integer>();
for(Integer key : map.keySet()) {
if(map.get(key)<=n) {
lst.add(key);
}
}
return lst;
}
When I sort a 2-D Array which is an argument to a function by Copying it to a 1-D Array, the output is correct but the iterations are repeating. Is my approach correct? I have used an Array "Sort" to copy both the unsorted Arrays & then sort this result set Array.
package learningJava;
import java.util.Arrays;
public class VarArgDemoThree
{
public static void main(String... args)
{
//First one D unsorted Array
int a[]= {10,2,56,17,81,92};
//Second one D unsorted Array
int b[]= {12,77,22,98,101,6};
//Static method Sort which to which both Arrays a & b are passed
Sort(a,b);
}
//Definition of Static method Sort
public static void Sort(int[]...x )//This method has a one d array as variable argument which is int[][] it get array (a[],b[])
{
//Declaring another one-d Sort of which the length is 12
int[] Sort = new int[x[0].length+x[1].length];
//Copying the one D array at location x[0] to another Array Sort using System.arraycopy
System.arraycopy(x[0], 0, Sort, 0, x[0].length);
//Copying the one D array at location x[1] to another Array Sort using System.arraycopy
System.arraycopy(x[1], 0, Sort, x[0].length, x[1].length);
//Sorting the Elements of the Array Sort
for(int i=0;i<Sort.length;i++)
{
int flag=0;
for(int j=i+1;j<Sort.length;j++)
{
if(Sort[i]>Sort[j])
{
int temp = Sort[i];
Sort[i] = Sort[j];
Sort[j] = temp;
flag=1;
}
}
System.out.print(Arrays.toString(Sort));
System.out.println();
if(flag==0)
{
break;
}
}
}
}
You are doing that loop more than it is needed.
just see the code below:
for(int i=0;i<Sort.length;i++) // line a
{
int flag=0;
for(int j=i+1;j<Sort.length;j++) // line b
{
if(Sort[i]>Sort[j])
{
int temp = Sort[i];
Sort[i] = Sort[j];
Sort[j] = temp;
flag=1;
}
}
System.out.print(Arrays.toString(Sort)); // line c
System.out.println();
in "line a" the loop is repeating until i == Sort.length.
in "line b" the loop is starting from j = i + 1 till j == Sort.length.
it is obvious that the last time the inner loop in "line b" does not run but "line c" that is printing Sort will run. that's why you're printing the array one extra time.
imagine the inner loop started from Sort.length + 1 till Sort.length.
to avoid that you would better to change the first loop to i < Sort.length - 1.
some more matters (which are optional):
why do you need flag ? you are looping till the end.
try to start the name of fields and local variables in lower case. for example use sort instead of Sort.
you can use System.out.print("something") and empty System.out.println() together, like System.out.println("something").
i<Sort.length-1 for the outer loop only works thanks..
int a[]= {10,6,18,23,97,188,67,45,52};
int b[]= {4,15,28,77,60,71,90,33,24};
for(int i=0;i<Sort.length-1;i++)
{
for(int j=i+1;j<Sort.length;j++)
{
if(Sort[i]>Sort[j])
{[![enter image description here][1]][1]
int temp = Sort[i];
Sort[i] = Sort[j];
Sort[j] = temp;
}
}
System.out.println(Arrays.toString(Sort));
}
[1]: https://i.stack.imgur.com/5jB1G.png
I am currently implementing a generic version of the longest increasing subsequence problem in Java. The method works as intended, but when I try to use Comparable[] instead of Integer[] (or int[]), the program won't compile. The error given is "Comparable cannot be cast to Integer". I understand the error and what it means, but I don't know how to fix it. Any help would be greatly appreciated :)
I have already tried making the method's return type a generic (>), but the problem is that Java does not allow generic array creation. I've tried just using Integer[] as my return type, and while that compiles and works properly, it's not what I want.
public class LIS {
public static void main(String[] args) {
final Integer[] arr = {-1, 2, 4, 2, 33, 4, 7, 8, 10, 7, 5, 4, 5, 5, 1};
final Integer[] LIS = (Integer[]) lis(arr);
for (int i : LIS) {
System.out.print(i + " ");
}
}
public static Comparable[] lis(Comparable[] arr) {
// We use Comparable[] so we can use interchangably with any Comparable type
final int N = arr.length;
// Java conveniently initializes array values to 0:
int[] lisEndingHere = new int[N];
for (int i = 0; i < N; i++) {
lisEndingHere[i] = 1;
int curMax = 0;
for (int j = 0; j <= i; j++) {
if (arr[i].compareTo(arr[j]) <= 0) continue;
if (lisEndingHere[j] > curMax) {
curMax = lisEndingHere[j];
}
}
lisEndingHere[i] += curMax;
}
// Find and return the longest increasing subsequence:
int max = 0;
for (int i = 0; i < N; i++) {
if (lisEndingHere[i] > max) max = lisEndingHere[i];
}
Comparable[] LIS = new Comparable[max];
for (int i = N-1; i >= 0 && max != 0; i--) {
if (lisEndingHere[i] == max) {
LIS[--max] = arr[i];
}
}
return LIS;
}
}
Just change the line
final Integer[] LIS = (Integer[]) lis(arr);
to
final Comparable[] LIS = lis(arr);
and also update the for loop.
Your method returns a Comparable array, so you cant downcast to an Integer array, but since the implementation of your numbers are Integers, they are still treated as such during runtime.
Setting the result to an Integer array is against the purpose of making a generic method anyways. For something to be passed to your method, it must have a compareTo method, and inherently has a toString method, and that satisfies everything you need the program to do.
There is nothing to fix here. Here:
Integer[] LIS = (Integer[]) lis(...)
Your method lis() returns an array of Comparable objects. A Comparable array isn't an Integer array! Thus that cast can't work conceptually.
Yes, that array contains Integer objects, but the array type isn't "array of integer".
You would have to iterate the resulting array, then you can cast the individual entries. But you can't cast the array type itself into something that it isn't!
Beyond that, you could use generics with lists instead.
I have looked around Stack Overflow and did some work myself with this code but doesn't matter whatever I do the answer prints to false but it has to print to true, also how can I Plot their running times as a function of their input size as scatter plots and then choose representative values of the size n, and run at least 5 tests for each size value n in the tests?
PrefixAverages1
import java.util.Arrays;
public class PrefixAverages1 {
static double array[] = new double[10];
public static void prefixAverages(){
for (int i = 0; i < 10; i++){
double s = array[i];
for (int j = 0; j < 10; j++){
s = s + array[j];
}
array[i] = s / (i + 1);
System.out.println(Arrays.toString(array));
}
}
public static double[] prefixAverages(double[] inArray) {
double[] outArray = new double[inArray.length];
return outArray;
}
public static void main(String... args) {
System.out.println(
Arrays.equals(
prefixAverages(new double[] {5, 6, 7, 8}),
new double[] {2, 2.5, 3.5, 4}
)
);
}
}
PrefixAverages2
import java.util.Arrays;
public class PrefixAverages2 {
static double array[] = new double[10];
public static void prefixAverages(){
double s = 0;
for (int i = 0; i < 10; i++){
s = s + array[i];
array[i] = s / (i + 1);
}
array[0] = 10;
System.out.println(Arrays.toString(array));
}
public static double[] prefixAverages(double[] inArray) {
double[] outArray = new double[inArray.length];
return outArray;
}
public static void main(String... args) {
System.out.println(
Arrays.equals(
prefixAverages(new double[] {3, 4, 5, 6}),
new double[] {2, 3.5, 4, 5}
)
);
}
}
First you must understand what Arrays.equals() method does. The Arrays.equals() method does comparison operation on two arrays, based on their content; not based on their size. First of all, let's look at your prefixAverages(float [] inArray) method. What you did there is just create a new float array of size equals to the size of the passing array, and then return that newly created array. And in the main method, you are comparing the returning array and a new array that you are supplying. But this is logically not correct. Since the returning array is an empty array; the Arrays.equals() method returns false, as the other array has some values in it. Even if the returning array do have some values, the Arrays.equals() method returns false if both contain different values. Always remember two arrays are equal if and only if they contain same values and the elements should be in the same order. ** Modify your program like this and it'll return **true
import java.util.Arrays;
public class PrefixAverages1 {
static double array[] = new double[10];
public static void prefixAverages(){
for (int i = 0; i < array.length; i++){
double s = array[i];
for (int j = 0; j < array.length; j++){
s = s + array[j];
}
array[i] = s / (i + 1);
System.out.println(Arrays.toString(array));
}
}
public static double[] prefixAverages(double[] inArray) {
double [] outArray = inArray;
return outArray;
}
public static void main(String... args) {
System.out.println(
Arrays.equals(
prefixAverages(new double[] {5, 6, 7, 8}),
new double[] {5, 6, 7,8}
)
);
}
}
One more thing. While using arrays in loop; always use array.length method to do comparison condition checking. Otherwise there is a high change of probability for an ArrayOutOfBoundsException condition.
I'm guessing because it's hard to understand what you are trying to do. But right now I'm not even sure how this code compiles, because you haven't defined any constructors, and you are (apparently attempting to) call a constructor (with the same name of a static class function, confusing AND bad form) with an array parameter. I'm guessing you meant to call the static method that takes a double[] parameter. (Right now, and here's the confusing part, it shouldn't compile because you should have to prefix the class name to call a static function.). Even that would fail, though, because that method returns an empty array of the same length of the input array. To top it all off, the "algorithm" section of your code is never even called.
I'd suggest just stepping through this in a debugger. That way you could see what the code is doing in real time and correct it if it's not what you meant.
Also, if you'd followed normal coding conventions (never name a function after the class; only constructors), it would be easier to spot errors like that.
Edit: I see how it compiles now. Still, naming the function after the class makes me think "constructor", along with everyone else on the planet.
The output you expect is incorrect; for the input 5, 6, 7, 8 the prefix average should be 5.0, 5.5, 6.0, 6.5.
After the first value 5, there has been one value (5). After the second value (6 + 5) there have been two values 11 (and 11 / 2 is 5.5). Then 6 (because 6+5+7 is 18) and 18/3 is 6. Finally 18+8 is 26 and 26/4 is 6.5
static double[] prefixAverages(double[] x) {
int len = x.length;
double[] arr = new double[len];
double sum = 0;
for (int i = 0; i < len; i++) {
sum += x[i];
arr[i] = sum / (i + 1);
}
System.out.println(Arrays.toString(arr));
return arr;
}
Is there anything as quick as this in java? ( quick in coding)
int [] a = {1..99};
or I have to go for this:
int [] a=new int[100];
for (int i=0;i <100;++i){
a[i]=i;
}
Since Java 8 this is possible:
int[] a = IntStream.range(1, 100).toArray();
(And shorter than the other java 8 answer .).
Another alternative if you use Java 8:
int[] array = new int[100];
Arrays.setAll(array, i -> i + 1);
The lambda expression accepts the index of the cell, and returns a value to put in that cell. In this case, cells 0 - 99 are assigned the values 1-100.
Java 8 allows to do that in one line with IntStream object and lambda expression:
int n = 10;
int[] values = new int[n];
IntStream.range(1,n+1).forEach(val -> values[val-1] = val);
Out of curiosity, I have tested the performance of two versions of that method - one with a loop and the other one using guava:
public int[] loop() {
int[] a = new int[100];
for (int i = 0; i < 100; ++i) {
a[i] = i;
}
return a;
}
public int[] guava() {
Set<Integer> set = ContiguousSet.create(Range.closed(0, 99), DiscreteDomains.integers());
int[] a = Ints.toArray(set);
return a;
}
Here are the results:
Benchmark Mean Mean error Var Units
loop 79.913 5.671 30.447 nsec/op
guava 814.753 46.359 2034.726 nsec/op
So the guava() method runs in 814 ns +/- 46ns vs. 80 ns +/- 5ns for the loop() method. So loop() is about 10x faster. If you call that method a few times, the 800 nanoseconds don't matter, if you call it very often, writing the loop is probably better.
I think that your code is the shortest and the simplest way. You might dont need to load extra libraries to get more "compact" code lines. The for loops are very simple (a truly O(n)) and legible, live and love them.
depending on the size you will have to loop, if its a small one you can do the following...
int[] intArray = new int[] {4,5,6,7,8};
im guessing for your size you dont want to have to type it all out so makes sense to create a loop and set it that way
If people do want to use the for-loop method, then you could shorten it to (side note):
int [] a = new int[100];
for (int i = 0; i < 100; a[i] = i++);
You can use Guava library, for something like this:
public class Test {
public static void main(String[] args) {
//one liner
int[] array = toArray(newLinkedList(concat(range(1, 10), range(500, 1000))));
//more readable
Iterable<Integer> values = concat(range(1, 10), range(500, 1000));
List<Integer> list = newLinkedList(values);
int[] array = toArray(list);
}
public static List<Integer> range(int min, int max) {
List<Integer> list = newLinkedList();
for (int i = min; i <= max; i++) {
list.add(i);
}
return list;
}
}
Updated: full example take from this post Fill arrays with ranges of numbers
You must use loop to initialize such a long array. There is not a shortcut method in Java as you expected.