Exception error in arrays - java

My code is intended to take in an array of ints and return an array of ints with a length of twice the original array's length, minus 2.
The returned array should have values 1/3 and 2/3 between any given two values in the original array.
For example input array:
{400, 500, 600}
will return:
{400,433,466,500,533,566,600}
The code I have is as follows:
public static void main(String[] args){
System.out.println("Problem 9 tests");
int[] arr7={300, 400, 500};
System.out.println(highDef(arr7));
System.out.println(" ");
public static int[] highDef(int[] original) {
int[] newarr = new int[original.length*3-2];
newarr[0]=original[0];
int count=0;
while (count!=newarr.length) {
int increment=(original[count+1]-original[count])/3;
newarr[count+1]=original[count]+increment;
newarr[count+2]=original[count]+(count*increment);
count+=1;
}
return newarr;

Haven't looked good enough the first time :)
Here you go:
public static void main(String[] args) {
System.out.println("Problem 9 tests");
int[] arr7 = {300, 400, 500};
System.out.println(Arrays.toString(highDef(arr7)));
System.out.println(" ");
}
public static int[] highDef(int[] original) {
int[] newarr = new int[original.length * 3 - 2];
newarr[original.length * 3 - 3] = original[original.length-1];
for(int i=0; i<original.length-1; i++){
newarr[i*3] = original[i];
int increment = (original[i+1] - original[i])/3;
newarr[i*3+1] = original[i] + increment;
newarr[i*3+2] = original[i] + increment*2;
}
return newarr;
}

With array out of bound exceptions, try to think of the last case.
In your example:
original.length = 3
newarr.length = (original.length * 3) - 2 = 7
while (count!=newarr.length) // this means: while count does not equal to 7. Therefore *Count* value can go upto 6
// imagine the last case, count = 6
newarr[count+2]=original[count]+(count*increment); // the problem is here
// count(6) + 2 = 8, which is out of bounds
same issue with this line: int increment=(original[count+1]-original[count])/3;
count will go upto 6 but original[count+1] = original[7] which is out of bound as well

Related

How to subtract two int arrays in Java?

I have this array in Java:
private int[] all = new int [] {0,1,2,3,4,5};
I want to set a new var that equal to all-{2,3,5} (equals {0,1,4})
Is there any build-in function that performs subtraction between two arrays?
You can code up set subtraction using Java 8 streams.
The idea is to construct a hash set of integers that you would like to exclude, and then run through the original array, check each element against the exclusion set in O(1), and keep only elements that should not be excluded.
int[] all=new int [] {0,1,2,3,4,5};
int[] ex=new int [] {2,3,5};
Set<Integer> exSet = IntStream.of(ex).boxed().collect(Collectors.toCollection(HashSet::new));
int[] res = IntStream.of(all).filter(val -> !exSet.contains(val)).toArray();
Demo.
I understood what you want to say and figured out a way to do that , what exactly you want.
If you use ArrayList then you could use removerAll() to remove or subtract.
Lets see this on the working code
import java.util.ArrayList;
public class removeAllInArrayList {
public static void main(String[] args) {
ArrayList <Integer> numbers = new ArrayList<Integer>();
numbers.add(0);
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
System.out.print("The number array contains:- \t");
display (numbers);
ArrayList <Integer> numbers2 = new ArrayList<Integer>();
numbers2.add(0);
numbers2.add(2);
numbers2.add(4);
numbers2.add(6);
System.out.print("The number2 array contains:- \t ");
display(numbers2);
System.out.println("Subtract number2 from number.");
numbers.removeAll(numbers2);
System.out.print("Now, number array contains:- \t");
display (numbers);
}
public static void display (ArrayList array){
for (int i =0 ; i < array.size() ; i++){
System.out.print(array.get(i) + " ");
}
System.out.println ();
}
}
The result of the following code is
The number array contains:- 0 1 2 3 4 5
The number2 array contains:- 0 2 4 6
Subtract number2 from number.
Now, number array contains:- 1 3 5
Hope this works , and helps to solve out the code.
I don't think there is such a build-in method. You can try to find some library which can do that, or write your own method:
public static int[] removeEqual(int[] a_arr, int[] b_arr) {
List<Integer> list = new ArrayList<>();
for (int a : a_arr) { list.add(a); }
Iterator<Integer> iter = list.iterator();
while(iter.hasNext()) {
int a = iter.next();
for (int b : b_arr) {
if (a == b) {iter.remove();}
}
}
int[] result = new int[list.size()];
for (int i = 0; i < list.size(); i++) {result[i] = list.get(i);}
return result;
}
Test
public static void main(String[] args) {
System.out.println("expected: [0, 1, 4], actual: " +
Arrays.toString(removeEqual(new int[] {0,1,2,3,4,5}, new int[] {2, 3, 5})));
}
Output: expected: [0, 1, 4], actual: [0, 1, 4]
You can do what you want with lists:
List<Integer> all = new ArrayList<>(Arrays.asList(0, 1, 2, 3, 4, 5));
List<Integer> toRemove = Arrays.asList(2, 3, 5);
all.removeAll(toRemove);
System.out.println(all); // [0, 1, 4]
In order to be able to remove elements from the all list, you should create it with the new ArrayList<>(anotherList) constructor, since the lists returned by Arrays.asList cannot be structurally modified.
I tested Streams vs Collections:
public static void main(String... args)
{
Random rand = new Random();
int[] all = new int[100000];
int[] ex = new int[50000];
fillArrays(rand, all, ex);
long start = System.currentTimeMillis();
testWithStreams(all, ex);
System.out.println(String.format("Streams: %d", System.currentTimeMillis() - start));
fillArrays(rand, all, ex);// Avoid any external optimization
start = System.currentTimeMillis();
testWithCollections(all, ex);
System.out.println(String.format("Collections: %d", System.currentTimeMillis() - start));
fillArrays(rand, all, ex);// Avoid any external optimization
start = System.currentTimeMillis();
testWithCollectionsToArray(all, ex);
System.out.println(String.format("Collections -> Array: %d", System.currentTimeMillis() - start));
fillArrays(rand, all, ex);// Avoid any external optimization
start = System.currentTimeMillis();
testWithStreamsAndSet(all, ex);
System.out.println(String.format("Streams + HashSet: %d", System.currentTimeMillis() - start));
}
private static void fillArrays(Random rand, int[] all, int[] ex)
{
for (int i = 0; i < all.length; i++)
{
all[i] = rand.nextInt();
}
for (int i = 0; i < ex.length; i++)
{
ex[i] = all[rand.nextInt(all.length)];
}
// System.out.println(String.format("all values: %d, %d, %d", all[0], all[1], all[2]));
// System.out.println(String.format("ex values: %d, %d, %d", ex[0], ex[1], ex[2]));
}
private static int[] testWithStreams(int[] all, int[] ex)
{
return Arrays.stream(all).filter(
(elementOfAll) -> Arrays.stream(ex).noneMatch(
(elementOfEx) -> elementOfAll == elementOfEx
)
).toArray();
}
private static List<Integer> testWithCollections(int[] all, int[] ex)
{
List<Integer> listOfAll = Arrays.stream(all).boxed().collect(Collectors.toList());
listOfAll.removeAll(Arrays.stream(ex).boxed().collect(Collectors.toList()));
return listOfAll;
}
private static int[] testWithCollectionsToArray(int[] all, int[] ex)
{
return testWithCollections(all, ex).stream().mapToInt((v) -> v).toArray();
}
private static int[] testWithStreamsAndSet(int[] all, int[] ex)
{
HashSet<Integer> exSet = Arrays.stream(ex).boxed().collect(Collectors.toCollection(HashSet::new));
return Arrays.stream(all).filter((element) -> !exSet.contains(element)).toArray();
}
The Output:
Streams: 13823
Collections: 2905
Collections -> Array: 2931
Streams + HashSet: 29
EDIT:
Added the example of dasblinkenlight

Rearrange an array in minimum and maximum java

Given an array of ints, I want to rearrange it alternately i.e. first element should be minimum, second should be maximum, third second-minimum, fourth second-maximum and so on...
I'm completely lost here...
Another method that doesn't require the space of three separate arrays but isn't as complex as reordering in place would be to sort the original array and then create a single new array. Then start iterating with a pointer to the current i-th index of the new array and pointers starting at the 0-th index and the last index of the sorted array.
public class Foo {
public static void main(String[] args) {
// Take your original array
int[] arr = { 1, 4, 5, 10, 6, 8, 3, 9 };
// Use the Arrays sort method to sort it into ascending order (note this mutates the array instance)
Arrays.sort(arr);
// Create a new array of the same length
int[] minMaxSorted = new int[arr.length];
// Iterate through the array (from the left and right at the same time)
for (int i = 0, min = 0, max = arr.length - 1; i < arr.length; i += 2, min++, max--) {
// the next minimum goes into minMaxSorted[i]
minMaxSorted[i] = arr[min];
// the next maximum goes into minMaxSorted[i + 1] ... but
// guard against index out of bounds for odd number arrays
if (i + 1 < minMaxSorted.length) {
minMaxSorted[i + 1] = arr[max];
}
}
System.out.println(Arrays.toString(minMaxSorted));
}
}
Hint:
Create two new arrays, 1st is sorted in assenting order and other is in descending order. Than select 1st element from 2nd array and 1st element from 1st array, repeat this selection until you reach half of both 1st and second array. and you will get your desired array.
Hope this will help you.
The approach in #Kaushal28's answer is the best approach for a beginner. It requires more space (2 extra copies of the array) but it is easy to understand and code.
An advanced programmer might consider sorting the array once, and then rearranging the elements. It should work, but the logic is complicated.
Hint: have you ever played "Clock Patience"?
This solution is based on Aaron Davis solution. I tried to make the looping easier to follow:
public class AltSort {
//list of array elements that were sorted
static Set<Integer> indexSorted = new HashSet<Integer>();
public static void main (String[] args) throws java.lang.Exception
{
//test case
int[] array = new int[]{7,22,4,67,5,11,-9,23,48, 3, 73, 1, 10};
System.out.println(Arrays.toString(altSort(array)));
//test case
array = new int[]{ 1, 4, 5, 10, 6, 8, 3, 9 };
System.out.println(Arrays.toString(altSort(array)));
}
private static int[] altSort(int[] array) {
if((array == null) || (array.length == 0)) {
System.err.println("Empty or null array can not be sorted.");
}
Arrays.sort(array);
//returned array
int[] sortedArray = new int[array.length];
int firstIndex = 0, lastIndex = array.length-1;
for (int i = 0; i < array.length; i++) {
if((i%2) == 0) { //even indices
sortedArray[i] = array[firstIndex++];
}
else {
sortedArray[i] = array[lastIndex --];
}
}
return sortedArray;
}
}
Here is another alternative: monitor the indices that have been sorted, and search the rest for the next min / max:
import java.util.Arrays;
import java.util.Set;
/**
* Demonstrates an option for sorting an int[] array as requested,
* by keeping a list of the array indices that has been sorted, and searching
* for the next min / max.
* This code is not optimal nor robust. It serves a demo for this option only.
*
*/
public class AltSort {
//list of array elements that were sorted
static Set<Integer> indexSorted ;
public static void main (String[] args) throws java.lang.Exception {
//test case
int[] array = new int[]{7,22,4,67,5,11,-9,23,48, 3, 73, 1, 10};
System.out.println(Arrays.toString(altSort2(array)));
//test case
array = new int[]{ 1, 4, 5, 10, 6, 8, 3, 9 };
System.out.println(Arrays.toString(altSort2(array)));
}
private static int[] altSort2(int[] array) {
if((array == null) || (array.length == 0)) {
System.err.println("Empty or null array can not be sorted.");
}
//returned array
int[] sortedArray = new int[array.length];
//flag indicating wether to look for min or max
boolean lookForMin = true;
int index = 0;
while(index < array.length) {
if(lookForMin) {
sortedArray[index] = lookForArrayMin(array);
}else {
sortedArray[index] = lookForArrayMax(array);
}
index++;
//alternate look for min / look for max
lookForMin = ! lookForMin;
}
return sortedArray;
}
private static int lookForArrayMin(int[] array) {
int minValue = Integer.MAX_VALUE;
int minValueIndex = 0;
for( int i =0; i< array.length; i++ ){
//if array[i] is min and was not sorted before, keep it as min
if( (array[i]< minValue) && ! indexSorted.contains(i) ) {
minValue = array[i]; //keep min
minValueIndex = i; //keep min index
}
}
//add the index to the list of sorted indices
indexSorted.add(minValueIndex);
return minValue;
}
private static int lookForArrayMax(int[] array) {
int maxValue = Integer.MIN_VALUE; //max value
int maxValueIndex = 0; //index of max value
for( int i =0; i< array.length; i++ ){
//if array[i] is max and was not sorted before, keep it as max
if( (array[i] > maxValue) && ! indexSorted.contains(i)) {
maxValue = array[i]; //keep max
maxValueIndex = i; //keep max index
}
}
//add the index to the list of sorted indices
indexSorted.add(maxValueIndex);
return maxValue;
}
}

Java : I want to change an integer array into a mathematical number [duplicate]

This question already has answers here:
Make individual array values to single number in Python [closed]
(3 answers)
Closed 6 years ago.
Here is my array, it consists of array of integers. Actually, these are the key of my HashMap which consists of some sentences or say "STRING" of a complete paragraph as a key value pair. Now I wanted to join those sentences from taking the key from the integer array one after another in given order.
int[] arr = {3, 2, 0, 5, 3};
HashMap<Integer, String> h = new HashMap<Integer, String>() {{
put(0,"This is my third sentence.");
put(3,"This is my first sentence.");
put(5,"This is my forth sentence.");
put(2,"This is my second sentence.");
}};
The final output should be all the sentences combined as mentioned order and outout should be like a paragraph as :
This is my first sentence.This is my second sentence.This is my third sentence.
This is my forth sentence.This is my first sentence.
Instead of converting the value to a character type you can perform math. For each digit in the array, the corresponding power of 10 is the array length (minus one) minus the index (because Java arrays use 0 based indexing and the last digit corresponds to 100). Something like,
int[] arr = { 3, 2, 0, 5, 3 };
int result = 0;
for (int i = 0; i < arr.length; i++) {
result += arr[i] * Math.pow(10, arr.length - i - 1);
}
System.out.println(result);
Output is (as expected)
32053
Optimization
It's possible to optimize the code further by keeping the current power of ten and dividing 10 while iterating each digit. This would also allow the use of a for-each loop like
int[] arr = { 3, 2, 0, 5, 3 };
int result = 0;
int pow = (int) Math.pow(10, arr.length - 1);
for (int digit : arr) {
result += digit * pow;
pow /= 10;
}
System.out.println(result);
Alternatively, iterate the digits from right to left and multiply pow by 10 on each iteration. That might look something like,
int result = 0;
int pow = 1;
for (int i = arr.length - 1; i >= 0; i--) {
result += arr[i] * pow;
pow *= 10;
}
And the above might also be written like
int result = 0;
for (int i = arr.length - 1, pow = 1; i >= 0; i--, pow *= 10) {
result += arr[i] * pow;
}
int number = Integer.parseInt(Arrays.stream(arr).mapToObj(String::valueOf).collect(Collectors.joining()));
Yet another way:
int[] arr = {3, 2, 0, 5, 3};
int i = Integer.parseInt(Arrays.toString(arr).replaceAll("[\\[,\\] ]", ""));
System.out.println(i); // prints 32053
Though fairly simple, you should have tried yourself.
Still providing a solution, just debug and understand it.
Working Code
public static void main(String[] args) throws Exception {
int[] arr = {3, 2, 0, 5, 3};
StringBuilder numberStr = new StringBuilder();
for (int item : arr) {
numberStr.append(item);
}
int finalInt = Integer.parseInt(numberStr.toString());
System.out.println(finalInt);
}
Output
32053
First convert the array into string by appending elements one by one and the convert string into integer. Try this code:
public class NewClass63 {
public static void main(String args[]){
int[] arr = {3, 2, 0, 5, 3};
StringBuffer s = new StringBuffer();
for(int i=0;i<arr.length;i++){
s.append(arr[i]);
}
int x = Integer.parseInt(s.toString());
System.out.println(x);
}
}
int[] array = {3,2,0,5,3};
String x = "";
for(int i = 0;i<=array.length-1;i++){
x = x + String.valueOf(array[i]);
}
System.out.println(Integer.parseInt(x));
use a loop:
int[] arr = { 3, 2, 0, 5, 3 };
String itotal = "";
for (int i = 0; i < arr.length; i++)
{
itotal=itotal + String.valueOf(arr[i]);
}
int a = Integer.parseInt(itotal);
There exist various ways.
If I am right, hidden assumption is that the higher element of integer array matches with higher digit of result integer.
int[] arr = {3, 2, 0, 5, 3};
int result = 0;
int power = (int) Math.pow(10, arr.length-1);
for(int element : arr){
result += element * power;
power /= 10;
}
Easiest solution answer is this.
Assume, each alphabet in the example is a single digit.
Empty Array {} : Expected value = 0
{a}: Expected value = a
{a,b}: Expected value = 10*a + b
{a,b,c}: Expected value = 10 * (10*a + b) + c
Code: Test this is online java compiler IDE
public class ConvertDigitArrayToNumber {
public static void main(String[] args) {
int[] arr = {3, 2, 0, 5, 3};
int value = 0;
for (int i = 0; i < arr.length; i++) {
value = (10*value) + arr[i];
}
System.out.println(value);
}
}
This is actually simpler and better solution than the other ones.
Only simple multiplication and addition (No powers).
No String conversions

How to fill an array with random numbers from 0 to 99 using the class Math?

I wrote the code, but there is no conversion from double to int.
public class Array {
public static void main(String[] args) {
int i;
int[] ar1 = new int[100];
for(int i = 0; i < ar1.length; i++) {
ar1[i] = int(Math.random() * 100);
System.out.print(ar1[i] + " ");
}
}
}
How can it be corrected?
ar1[i] = (int)(Math.random() * 100);
Conversion in Java looks like cast in C.
It should be like
ar1[i] = (int)(Math.random() * 100);
When you cast, cast type should be in brackets e.g. (cast type)value
Try this:
package studing;
public class Array {
public static void main(String[] args) {
Random r = new Random();
int[] ar1 = new int[100];
for(int i = 0; i < ar1.length; i++) {
ar1[i] = r.nextInt(100);
System.out.print(ar1[i] + " ");
}
}
}
Why?
Using Math.random() can return 1, this means Math.random()*100 can return 100, but OP asked for maximum 99! Using nextInt(100) is exclusive 100, it can only return values from 0 to 99.
Math.random() can not return -0.000001 that would be round to 0 and 1.0000001 can not be returned that should round to 1. So you have less chance to get 0 or 99 than all the numbers between. This way it is not realy random, to guess "its not 0 or 99" is more true than "its not 1 or 98".
Also it do not make a detour via casting and mathematic operations you don't realy need, hey you dont need to strictfp on amd-cpus or old intel-cpus.
This is not actually using the java.lang.Math class, but in Java 8 a random array can also be created in this fashion:
int[] random = new Random().ints(100, 0, 100).toArray();
My solution uses Random class instead of Math.random. Here it is.
private static int[] generateArray(int min, int max) { // generate a random size array with random numbers
Random rd = new Random(); // random class will be used
int randomSize = min + rd.nextInt(max); // first decide the array size (randomly, of course)
System.out.println("Random array size: " + randomSize);
int[] array = new int[randomSize]; // create an array of that size
for (int i = 0; i < randomSize; i++) { // iterate over the created array
array[i] = min + rd.nextInt(max); // fill the cells randomly
}
return array;
}

Java passing of parameter

Can someone please explain in a little detail to me why this code prints 2?
import java.util.*;
public class TestCode2 {
public static void main(String[] args) {
int[][] array = {{1,2,3,4}, {5,6,7,8}};
System.out.println(m1(array)[0]);
// System.out.println(m2(array)[1]);
}
public static int[] m1(int[][] m) {
int[] result = new int[2];
result[0] = m.length;
result[1] = m[0].length;
return result;
}
}
int[][] array = {{1,2,3,4}, {5,6,7,8}};
=> int[][] array = {arrayOne, arrayTwo};
The length of array is 2 because it's just a bi-dimensionnal array which contains 2 sub arrays (which have both a length of 4).
So
array.length = 2;
array[0].length = length of arrayOne (i.e: length of {1,2,3,4}) = 4
array[1].length = length of arrayTwo (i.e: length of {5,6,7,8}) = 4
To summarize :
public static int[] m1(int[][] m) {
int[] result = new int[2];
result[0] = m.length; //m.length = 2
result[1] = m[0].length; //m[0].length = length of {1,2,3,4} = 4
return result; //{2,4}
}
Then you just print the first element of this array returned, i.e 2.
This is a 2d array so :
when you do like this :
int [][] array = {{1,2,3,4},{5,6,7,8}}
int a=array.length; \ i.e a=2
this is because the array treats the 2 sets as its element means {1,2,3,4} and {5,6,7,8} are considered as single element
sorry for wrong format as i am using mobile
m1() is taking 2D array as i/p & returning a (1D) array with first element as length of the i/p array, which - in this case is 2; Hence 2.

Categories