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.
Related
I am pretty new in this world, and I must say sometimes things that looks easy are pretty harsh.
I am stuck with a task that entails dealing with an array and for-loops.
I should iterate over the array and for every iteration step print a different random string. My current code is not working correctly, the only thing I'm getting a random item and the same index printed multiple times.
My output right now:
relax
2
2
2
2
How can I fix that and get a correct randomized output?
My code:
public static void main(String[] args) {
int i;
String Cofee[] = {"pick it","drink it","relax","put it in a cup",};
java.util.Random randomGenerator = new java.util.Random();
int x = Cofee.length;
int y = randomGenerator.nextInt(x);
String frase = Cofee[y] ;
System.out.println(frase);
for(i = 0; i < Cofee.length; i++)
System.out.println(y);
}
You assign a value to y once, and you print y repeatedly. The value of y doesn't change. To do that, you would need to call randomGenerator.nextInt(x) for each iteration of the loop!
However, if you want to randomize and print the array, use:
public static void main(String[] args)
{
String[] coffee = {"pick it","drink it","relax","put it in a cup",};
// this wraps the array,
// so modifications to the list are also applied to the array
List<String> coffeeList = Arrays.asList(coffee);
Collections.shuffle(coffeeList);
for(String value : coffee)
System.out.println(value);
}
As an aside, don't use String coffee[], but use String[] coffee. Although Java allows putting the array type after the variable name, it is considered bad form.
Or use a list directly:
public static void main(String[] args)
{
List<String> coffeeList = Arrays.asList("pick it","drink it","relax","put it in a cup");
Collections.shuffle(coffeeList);
for(String value : coffeeList)
System.out.println(value);
}
For that, you can implement a shuffling algorithm.
It's not so scaring as it might sound at first. One of the famous classic shuffling algorithms, Fisher–Yates shuffle is relatively easy to grasp.
The core idea: iterate over the given array from 0 to the very last index, and for each index swap the element that corresponds to the randomly generated index between 0 and the current index (i) with the element under the current index.
Also, I would advise creating a separate array representing indices and shuffle it in order to preserve the array of string its initial state (you can omit this part and change the code accordingly if you don't need this).
That's how it might be implemented:
public static final Random RANDOM = new Random(); // we need an instance for random to generate indices
A Fisher–Yates shuffle implementation:
public static void shuffle(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int j = RANDOM.nextInt(i + 1); // generating index in range [0, i]
swap(arr, i, j); // swapping elements `i` and `j`
}
}
Helper-method for swapping elements:
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
Usage-example:
String[] coffee = {"pick it","drink it","relax","put it in a cup"};
int[] indices = new int[coffee.length];
for (int i = 0; i < indices.length; i++) indices[i] = i; // or Arrays.setAll(indices, i -> i); if you're compfortable with lambda expressions
shuffle(indices);
for (int i = 0; i < coffee.length; i++) {
String next = coffee[indices[i]];
System.out.println(next);
}
Output:
drink it
pick it
put it in a cup
relax
I have an exercise to sort an array (type int) so I can get the largest number possible.
An example:
1,3,9 ==> 931
1,3,9,60 ==> 96031
So here is my idea: It is impossible to just sort the array to form the number that I wanted. So I can check the first number of each element in array, using the very same idea as bubble sort, just one small difference is that i use the first element to check instead of just arr[i]. But I still want to know beside using my idea, are there any other way (more efficiency). Even if your idea are the very same with my idea but you have something upgrade.
Thank you very much
It is impossible to just sort the array to form the number that I wanted.
Actually, it isn't impossible.
What you need is to design and implement an ordering that will result in the (decimal) numbers that will make the final number to be largest to sort first; e.g. for the numbers in your question, the ordering is:
9 < 60 < 3 < 1
You just need to work out exactly what the required ordering is for all possible non-negative integers. Once you have worked it out, code a Comparator class that implements the ordering.
Hint: You would be able to specify the ordering using recursion ...
Solution
For the descending order we multiply here by -1 each value in the array then sort the array and then multiply back with -1.
Ultimately we build the result string with string concatenation and print it out
import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
int[] array = {3,1,9};
for (int l = 0; l < array.length; l++){
array[l] = array[l]*-1;
}
Arrays.sort(array);
for (int l = 0; l < array.length; l++){
array[l] = array[l]*-1;
}
String res = "";
for(int i = 0; i < array.length; i++){
res+=array[i];
}
System.out.println(res);
}
}
Output
931
Alternatively
Or as #Matt has mentioned in the comments you can basically concat the string in reverse order. Then there is no need anymore for the ascending to descending transformation with *-1
import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
int[] array = {
9,
1,
3
};
String res = "";
Arrays.sort(array);
for (int l = array.length - 1; l >= 0; l--) {
res += array[l];
}
System.out.println(res);
}
}
Hope it will work as per your requirement->
public static void main(String[] args) {
Integer[] arr = {1,3,3,9,60 };
List<Integer> flat = Arrays.stream(arr).sorted((a, b) -> findfirst(b) - findfirst(a)).collect(Collectors.toList());
System.out.println(flat);
}
private static int findfirst(Integer a) {
int val = a;
if(val>=10) {
while (val >= 10) {
val = val / 10;
}
}
return val;
}
A lot of problems become easier when using Java streams. In this case you could convert all numbers to String and then sort in an order which picks the higher String value of two pairings, then finally join each number to one long one.
This works for your test data, but does NOT work for other data-sets:
List<Integer> list1 = List.of(1,3,9,60);
Comparator<String> compare1 = Comparator.reverseOrder();
String num1 = list1.stream().map(String::valueOf).sorted(compare1).collect(Collectors.joining(""));
The comparator Comparator.reverseOrder() does not work for numbers of different length which start with same values, so a more complex compare function is needed which concatenates values to decide ordering, something like this which implies that "459" > "45" > "451"
List<Integer> list2 = List.of(1,45,451,449,450,9, 4, 459);
Comparator<String> compare = (a,b) -> (b+a).substring(0, Math.max(a.length(), b.length())).compareTo((a+b).substring(0, Math.max(a.length(), b.length())));
String num2 = list2.stream().map(String::valueOf).sorted(compare).collect(Collectors.joining(""));
... perhaps.
compare first number of each int then if it is the biggest put it at beginning then you continue, if first char is equal step into the second etc etc the bigest win, if it same at max-char-size. the first selected would be pushed then the second one immediatly after as you already know.
In that maneer 9 > 60 cuz 960>609 the first char will always be the biggest in that case when u concat.
it's > 9 < not > 09 <
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());
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Consider input [3,2,4] and target is 6. I added (3,0) and (2,1) to the map and when I come to 4 and calculate value as 6 - 4 as 2 and when I check if 2 is a key present in map or not, it does not go in if loop.
I should get output as [1,2] which are the indices for 2 and 4 respectively
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
int[] arr = new int[2];
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0;i < len; i++)
{
int value = nums[i] - target;
if(map.containsKey(value))
{
System.out.println("Hello");
arr[0] = value;
arr[1] = map.get(value);
return arr;
}
else
{
map.put(nums[i],i);
}
}
return null;
}
I don't get where the problem is, please help me out
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice. Consider input [3,2,4] and target is 6. I added (3,0) and (2,1) to the map and when I come to 4 and calculate value as 6 - 4 as 2 and when I check if 2 is a key present in map or not, it does not go in if loop.
Okay, let's take a step back for a second.
You have a list of values, [3,2,4]. You need to know which two will add up 6, well, by looking at it we know that the answer should be [1,2] (values 2 and 4)
The question now is, how do you do that programmatically
The solution is (to be honest), very simple, you need two loops, this allows you to compare each element in the list with every other element in the list
for (int outter = 0; outter < values.length; outter++) {
int outterValue = values[outter];
for (int inner = 0; inner < values.length; inner++) {
if (inner != outter) { // Don't want to compare the same index
int innerValue = values[inner];
if (innerValue + outterValue == targetValue) {
// The outter and inner indices now form the answer
}
}
}
}
While not highly efficient (yes, it would be easy to optimise the inner loop, but given the OP's current attempt, I forewent it), this is VERY simple example of how you might achieve what is actually a very common problem
int value = nums[i] - target;
Your subtraction is backwards, as nums[i] is probably smaller than target. So value is getting set to a negative number. The following would be better:
int value = target - nums[i];
(Fixing this won't fix your whole program, but it explains why you're getting the behavior that you are.)
This code for twoSum might help you. For the inputs of integer array, it will return the indices of the array if the sum of the values = target.
public static int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
outerloop:
for(int i = 0; i < nums.length; i++){
for(int j = 0; j < nums.length; j++){
if((nums[i]+nums[j]) == target){
indices[0] = i;
indices[1] = j;
break outerloop;
}
}
}
return indices;
}
You can call the function using
int[] num = {1,2,3};
int[] out = twoSum(num,4);
System.out.println(out[0]);
System.out.println(out[1]);
Output:
0
2
You should update the way you compute for the value as follows:
int value = target - nums[i];
You can also check this video if you want to better visualize it. It includes Brute force and Linear approach:
class ArrayApp{
public static void main(final String[] args){
long [] arr;
arr= new long[100];
int i;
arr[0]=112;
arr[1]=111;
for(i=0;i<arr;i++) {
System.out.println(arr[i]);
}
}
}
I get this error,
ArrayApp.java:10: operator < cannot be applied to int,long[]
for(i=0;i<arr;i++) {
^
You need to use the size of the array, which would be arr.length.
for (int i = 0; i < arr.length; ++i)
As of Java 1.5, you can also use the for each loop if you just need access to the array data.
for ( long l : arr )
{
System.out.println(l);
}
arr is an object of long[] , you can't compare int with it.
Try arr.length
Alternatively You should go for
for(long item:arr){
System.out.println(item);
}
You want arr.length
The question has to be seen in the context of a previous question!
From this former question I remember that you actually have a logical array inside a physical array. The last element of the logical array is not arr.length but 2, because you've "added" two values to the logical array.
In this case, you can't use array.length for the iteration but again need another variable that store the actual position of "the last value" (1, in your case):
long[] arr;
arr= new long[100];
int i;
arr[0]=112;
arr[1]=111;
int nElem = 2; // you added 2 values to your "logical" array
for(i=0; i<=nElem; i++) {
System.out.println(arr[i]);
}
Note - I guess, you're actually learning the Java language and/or programming. Later on you'll find it much easier to not use arrays for this task but List objects. An equaivalent with List will look like this:
List<Integer> values = new ArrayList<Integer>();
values.add(112);
values.add(111);
for (Integer value:values)
System.out.println(value);
Long arr = new Long[100];
arr[0]=112;
arr[1]=111;
for(int i=0;i<arr.length;i++) {
if (arr[i] != null ) {
System.out.println(arr[i]);
}
}
if you want to show only those which are filled.
You can solve your problem using one line of code:
Arrays.asList(arr).toString().replace("[", "").replace("]", "").replace(", ", "\n");
See http://java.dzone.com/articles/useful-abuse for more similar tricks.