Reverse Array (HackerRank) [duplicate] - java

This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 3 years ago.
Am I leaning in the right direction with my code? I'm currently working on hacker rank and am on the easy section of data structures yet I still am confused about how to reverse this array!
Out of all my attempts, I like these two that I did. Check it out.
one attempt:
two attempts:

You can reverse array in two ways
Either by fetching elements from last to start index and putting elements into new array
for example
int[] b = new int[n];
for(int i = n-1; i>=0 ; i--){
n[i] = arrayTobeReverse[i];
}
for more you can visit : https://www.geeksforgeeks.org/reverse-an-array-in-java/
By using Collection.reverse() method first you have to convert array into List using Arrays.asList(array) you can create List using array and then reverse the List.
for example :
import java.util.*;
public class ReverseDemo
{
public static void main(String[] args)
{
// Let us create a list of strings
List<String> mylist = new ArrayList<String>();
mylist.add("practice");
mylist.add("code");
mylist.add("quiz");
mylist.add("geeksforgeeks");
System.out.println("Original List : " + mylist);
// Here we are using reverse() method
// to reverse the element order of mylist
Collections.reverse(mylist);
System.out.println("Modified List: " + mylist);
}
}

You should be walking down the input array, then populating the target array in the opposite direction:
public static int[] reverseArray(int[] a) {
int[] b = new int[a.length];
for (int i=0; i < a.length; ++i) {
b[i] = a[a.length-i-1];
}
return b;
}
Just for fun, here is way to reverse the order of an original array, without using any extra storage:
// give input int[] a
for (int i=0; i < a.length / 2; ++i) {
a[i] = a[a.length-i-1];
}
Note that this approach just walks down half of the array, and swaps elements about the median.

Related

Take out sub set of indexes from array of type integer [duplicate]

This question already has answers here:
How to convert an ArrayList containing Integers to primitive int array?
(19 answers)
Closed 1 year ago.
So I have a List in which there are say 2 elements (suppose [1,2]), now the return type of method is int[] so I need to convert this Listto int[].
Here is my so far code,
public int[] twoSum(int[] nums, int target) {
List<Integer> l1 = new ArrayList<Integer>();
int lengthOfnums = nums.length;
int[] indexOfNums = new int[nums.length];
if(lengthOfnums != 0)
{
for(int i=0; i <=lengthOfnums-1; i++)
{
for(int j =1; j<=lengthOfnums-1;j++)
{
if(nums[i] + nums[j] ==target)
{
//l1.add(i);
//l1.add(j);
indexOfNums[i]=i;
indexOfNums[i+1]=j; // here somewhere logic goes boom
}
}
}
}
return indexOfNums;
}
When I use (to operate on l1 arrayList)
Integer[] boxed = l1.stream().filter(Objects::nonNull).toArray(Integer[]::new);
indexOfNums = ArrayUtils.toPrimitive(boxed);
It gives output something like - [I#6bf2d08e, I think it is something related to address of memory, (not sure on this part).
So this one didn't work.
Also I can not use the for loop as I have to think about the complexity O(n) for my method.
Already complexity has reached to O(n)2 (square).
**What I want is **
if sum of two numbers is target then I want to get the index of those numbers.
This can be done by converting the Stream<Integer> into a IntStream which has a toArray() method which generates an int[]
l1.stream().filter(Objects::nonNull).mapToInt(Integer::intValue).toArray()

How to set size of two dimensional ArrayList?

So I'm trying to make an two dimensional ArrayList which has a set amount of ArrayLists, then each of those ArrayLists can contain as much as needed. I'm aware that arrays dynamically change size, but I'm trying to guarantee that is has at least a certain size in this case.
ArrayList<ArrayList<Integer>> integers = new ArrayList<ArrayList<Integer>>(10);
This doesn't work. I want to be able to set the location of a new Integer to one of the first dimension's indices, like so:
integers.get(7).add(new Integer(42));
This just gives me an IndexOutOfBoundsException, as though there are no Integer ArrayLists within the ArrayList. Is there a way to do this? I'm sure it's something simple I'm not seeing.
Array lists do not work like this. They are not arrays.
The list you created is backed by array of at least 10 elements, but itself it does not contain any, so you cannot refer to 7th or actually any one element.
integers.size() would return 0
integers.isEmpty() would return true
integers.get(0) would throw
Moreover, the list you initialized needs to be filled with lists themselves:
for (int i = 0; i < 10; ++i) {
row = new ArrayList<Integer>()
integers.add(row);
}
// now integers is a 10-element list of empty lists
Alternatively you could use primitive arrays (if you want to have a fixed-size rectangle).
int integers[][] = new int[10][];
for (int i = 0; i < integers.length; ++i) {
integers[i] = new int[10]; // rows are initialized to 0, as int is primitive
}
for (final int[] arr : integers) {
System.out.println(Arrays.toString(arr));
}
You can use a nested loop for this. Here is a short example:
import java.util.ArrayList;
public class PopulateArray {
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> integers = new ArrayList<ArrayList<Integer>>();
int num_arrays_ to_populate = 10;
int num_indices_to_populate = 10;
for(int i = 0; i < num_arrays_to_populate; i++) {
integers.add(new ArrayList<Integer>());
for(int j = 0; j < num_indices_to_populate; j++) {
integers.get(i).add(0);
}
}
}
}
This would create an ArrayList of ArrayLists of ints and fill the top ArrayList with 10 ArrayLists and put a 0 in the first 10 cells of each. Obviously you can change any of those numbers to do what you want.
Note/Disclaimer: I wrote this on my phone, so if I missed a brace or semicolon, just comment and I’ll add it. The logic is there, though.

Changing Array to ArrayList [duplicate]

This question already has answers here:
How to convert int[] into List<Integer> in Java?
(21 answers)
Closed 5 years ago.
I am trying to find duplicate element in an array. I have already solved it using traversing the array. But now i want to convert array to arraylist and use contains keyword of arraylist.
I am not able to convert array to arraylist and use the contains keyword. please look in following code:
public void findDuplicate2() {
int arr[] = { 1, 2, 3, 4, 5, 3, 7, 5 };
ArrayList<int[]> arrlist = new ArrayList<>(Arrays.asList(arr));
for (i = 0; i < len; i++) {
if (arrlist.contains(arr[i]))
System.out.println(arr[i]);
else
System.out.println("no duplicate" + arr[i]);
}
}
There are a number of problems with your code:
You are creating an ArrayList<int[]>, that is, an array list of arrays of int. This list contains one array, namely the one you started out from. I don’t think this was what you intended. My guess is you wanted an ArrayList<Integer> containing the numbers from the array. khelwood’s link should help you out.
You haven’t declared i nor len. I suggest you use for (int i = 0; i < arr.length; i++).
arrlist.contains(arr[i]) always returns false since a list of arrays cannot contain a number (the numbers inside the array are not searched). It’s a design problem with ArrayList that you can ask for whether it contains an element of the wrong type (there are historical reasons for this). If you change the arraylist to ArrayList<Integer> as I suggested above, it will work, though.
Once you get the above to work, arrlist.contains(arr[i]) will always return true since each number from the array will be in the array list, also the ones that are not duplicates.
Here your arrlist variable is of type int[]. Here your arrlist size is 1(the entire input array as single entry).
So, you can only check the existence of any integer array in the list by using contains method of arrlist. if (arrlist.contains(arr)) //returns true in your case
An easier way to find dublicates is this one:
public void findDuplicate2(){
int arr[] = {1,2,3,4,5,3,7,5};
for (int i = 0; i < arr.length; i++) {
boolean dublicate = false;
for (int j = 0; j < arr.length; j++) {
if(arr[i] == arr[j] && i != j){
System.out.println(arr[i]);
dublicate = true;
break;
}
}
if(!dublicate)
System.out.println("No dublicate " + arr[i]);
}
}
In your code the arraylist contains one element, the array arr. You can check this with
System.out.println(arrlist.get(0));
System.out.println(arrlist.get(1));
The right way would be to transfer each element of arr to arraylist...

Randomize array of Strings, but without repeating elements [duplicate]

This question already has answers here:
Random shuffling of an array
(31 answers)
Closed 8 years ago.
I'd like to ask how should I implement a method in Java that takes all the elements from an array and shuffle them. Think like a deck of playing cards.
This is my try:
// a is an array of type String
public void randomize()
{
for(int i=0; i<k; ++i)
{
int idx = new Random().nextInt(k);
String random = (a[idx]);
System.out.println(random);
}
}
You can use Collections.shuffle(). First convert your array to a List
Using built-in methods is probably the easiest and cleanest solution:
Collections.shuffle(Arrays.asList(a)); //shuffles the original array too
This works because the asList method (emphasis mine):
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)
You mean somethin like this one? Or you are looking for something more complex?
static void shuffleArray(String[] ar)
{
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}

Iterating through ArrayList to get 5 Largest Numbers

Yes, this is homework, but I need some help with it. I have been able to make it sort through the highest number, but none of the numbers are correct after that. List of numbers: http://pastebin.com/Ss1WFGv1
Right now, we are learning arrays, so is this simply trying to shoot a fly with a cannonball?
package hw2;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class HW2 {
public static ArrayList<Integer> nums1 = new ArrayList<Integer>();
public static int size = 0;
public static void main(String[] args) throws Exception {
ArrayList<Integer> sortedNums = new ArrayList<Integer>();
readFile();
System.out.println("Name: Jay Bhagat" + "\n" + "Email: xxxxxx");
size = nums1.size();
for(int l = 0; l<=10;l++){
nums1.set(sortThis(nums1, l), 90009);
System.out.println("\n\n");
}
// for (int k = 0; k <= size - 1; k++) {
// System.out.println("Number " + (k + 1) + sortedNums.get(k));
//
// }
}
public static void readFile() throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("L:\\numbers.txt"));
while (reader.readLine() != null) {
nums1.add(Integer.parseInt((reader.readLine())));
}
reader.close();
}
public static int sortThis(ArrayList<Integer> current, int offset) {
int j = 0;
int tempNum = 0;
int curNum = 0;
int finalIndex = 0;
int prevIndex = 0;
int curIndex = 0;
for (j = 0; j < size-offset; j++) {
curIndex = j;
nums1.trimToSize();
curNum = current.get(j);
//Thread.sleep(1000);
if(curNum!=90009){
if (curNum > tempNum) {
tempNum = curNum;
System.out.println(tempNum);
prevIndex = j;
finalIndex = prevIndex;
}
if (curNum < tempNum) {
finalIndex = prevIndex;
}
}
}
return finalIndex;
}
}
An approach that lets you make just one pass through the list and doesn't require sorting:
Declare an array of 5 integers: int[] largest = new int[5];
Put the first 5 elements in the ArrayList into largest.
Starting with the 6th element, look at each element N in the ArrayList, and if N is larger than any element in largest, throw out the smallest number currently in largest and replace it with N.
If you need to exclude duplicates, the algorithm can be modified easily (just skip over any ArrayList element that's already in largest).
Why not use Collections.sort(List list) or Arrays.Sort(arr). This will save much of effort. Or is it part of your task?
Assuming your collection is sorted, and you want the last 5 elements, try this out:
for (int i = sortedNums.size() - 5; i < sortedNums.size(); ++i) {
System.err.println(sortedNums.get(i));
}
How I would go about doing this:
Create a temporary ArrayList, as a copy of the initial one.
After each largest element is found, remove it from the temporary ArrayList and add it to your 5 largest numbers
Repeat until complete
edit* This does not require your elements to be sorted, and has a fairly poor efficiency as a result
I assume you do not have the liberty to use sort and suchlike, considering this is a homework. So here is outline of an algorithm that you can try to implement
create an array of five integers (we will keep this sorted)
for each element in the list
find the index of the element in the array that it is greater than
if no such element exists in the array (i.e. it is smaller than all elements in the array)
continue on to the next element in the list
else
push all elements in the array to one index below, letting them fall off the
edge if need be (e.g. if the number in list is 42 and the array has
45 and 40 at index 3 and 2 respectively then
move arr[1] to arr[0], and arr[2] (40) to arr[1] and set arr[2] = 42)
end if
end for
At the end the array will have the five elements
I will leave one question for you to answer (it is important): what should you set the array to initially?
You only need two lines of code:
Collections.sort(nums1);
List<Integer> high5 = nums1.subList(nums1.size() - 5, nums1.size());
If you must "do it yourself", the simplest way to sort is a bubble sort:
iterate over the list
swap adjacent numbers if they are in the wrong order
repeat n times
Not efficient but very easy to code.

Categories