Java ArrayIndexOutOfBoundsException MOOC Helsinki - where is the mistake in my code? - java

I've been searching for an answer, but without any results. I know that this exception means that I'm trying to reach nonexistent array element, but I just can't see it.
It's excercise 104 from MOOC Helsinki, you can read it here
http://mooc.cs.helsinki.fi/programming-part1/material-2013/week-6?noredirect=1
I'm supposed to create sorting algorithm by creating five methods one after another. I've created first four, but things go south with the final one. I have no idea whether it's just matter of changing a single character, or the whole construction is flawed.
I would be grateful for help, feel free to comment on my code, but if it's possible do not overwrite the whole thing, I don't want solving it for me, just some hints and help.
import java.util.Arrays;
public class Main {
public static int smallest(int[] array) {
int result = array[0];
int position = 0;
for (int i = 0; i < (array.length); i++) {
if (result > array[i]) {
result = array[i];
position = i;
}
}
return result;
}
public static int indexOfTheSmallest(int[] array) {
int result = array[0];
int position = 0;
for (int i = 0; i < (array.length); i++) {
if (result > array[i]) {
result = array[i];
position = i;
}
}
return position;
}
public static int indexOfTheSmallestStartingFrom(int[] array, int index) {
int result = array[index];
int position = 0;
for (int i = index; i < array.length; i++) {
if (result > array[i]) {
result = array[i];
position = i;
}
}
return position;
}
public static void swap(int[] array, int index1, int index2) {
int a = array[index1];
int b = array[index2];
array[index1] = b;
array[index2] = a;
}
public static void sort(int[] array) {
int temp;
for (int x = 0; x < array.length; x++) {
System.out.println(Arrays.toString(array));
temp = indexOfTheSmallestStartingFrom(array, x);
swap(array, array[x], temp);
}
}
public static void main(String[] args) {
int[] values = {8, 3, 7, 9, 1, 2, 4};
sort(values);
}
}

change swap(array, array[x], temp); to
swap(array, x, temp);

Try this out,
import java.util.Arrays;
public class Main {
public static int smallest(int[] array) {
int result = array[0];
int position = 0;
for (int i = 0; i < (array.length); i++) {
if (result > array[i]) {
result = array[i];
position = i;
}
}
return result;
}
public static int indexOfTheSmallest(int[] array) {
int result = array[0];
int position = 0;
for (int i = 0; i < (array.length); i++) {
if (result > array[i]) {
result = array[i];
position = i;
}
}
return position;
}
public static int indexOfTheSmallestStartingFrom(int[] array, int index) {
int result = array[index];
int position = 0;
for (int i = index; i < array.length; i++) {
if (result > array[i]) {
result = array[i];
position = i;
}
}
return position;
}
public static void swap( int index1, int index2) {
int a = array[index1];
int b = array[index2];
array[index1] = b;
array[index2] = a;
}
public static void sort() {
int temp;
for (int x = 0; x < array.length; x++) {
System.out.println(Arrays.toString(array));
temp = indexOfTheSmallestStartingFrom(array, x);
swap( x, temp);
}
}
static int [] array= {8, 3, 7, 9, 1, 2, 4};
public static void main(String[] args) {
sort();
}
}
swap function was making changes but they weren't reflected because you were using pass-by-value.
I haven't touched the algorithm because the output is not as expected.

Related

Method to find second highest number in an array in java

Getting output of 0 each time when im ment to get 3 looked over my code my not sure where i have gone wrong i can do it without using a method i know but just trying to practice java
public class App {
public static int second(int a[],int n) {
int[] arr = new int [n];
int temp;
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr[n-2];
}
public static void main(String[] args) {
int[] arr = {1,3,2,5,3};
int n = 5;
int result = second(arr,n);
System.out.println(result);
}
}
You could change the array parameter name arr and remove the declaration or copy the values from a to arr.
public static int second(int arr[],int n) {
int temp;
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr[n-2];
}
The reason you get zero is because the primitive int cannot be null. So, when you create the array of length 5, it starts out filled with zeroes.
Doing it by using streams:
public static int second(int a[]) {
return Arrays.stream(a)
.sorted()
.skip(a.length - 2)
.findFirst()
.getAsInt();
}
I removed the second argument. It sorts your array and skips all the elements prior to the one you want, before picking the now first element.
public static int second(int[] arr) {
int highest = arr[0];
int second = 0;
for (int i = 1; i < arr.length; i++) {
int j = arr[i];
if (j >= highest) {
highest = j;
} else if (j > second) {
second = j;
}
}
return second;
}
public static void main(String[] args) {
int[] arr = {1, 3, 2, 5, 3};
int result = second(arr);
System.out.println(result);
}
Here is one way that doesn't require sorting.
int[] arr = { 10, 2, 3, 19, 2, 3, 5 };
System.out.println(second(arr));
prints
10
set largest to the first value in the array
set secondLargest to the smallest possible
now iterate thru the array.
if the current value is greater than largest:
replace secondLargest with Largest
replace largest with current value
else check to see if current value is greater than secondLargest and assign if true.
public static int second(int arr[]) {
int largest = arr[0];
int secondLargest = Integer.MIN_VALUE;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest) {
secondLargest = arr[i];
}
}
return secondLargest;
}
public static int second(int arr[],int n) {
int temp;
if(arr.length < 2) {
return -1;
}
else {
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr[n-2];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] = {23,14,56,77,66,67};
int high = 0;
int sec = 0;
for(int i = 0 ; i <a.length; i++){
if(high < a[i]){
sec = high;
high = a[i];
}
else if(sec < a[i]){
sec = a[i];
}
}
System.out.println("the first highest number is " + high);
System.out.println("the second highest number is " + sec);
}
}
public static int sec(){
int arr[] = {12,3,67,4,5,65};
int high = 0;
int low = 0;
for(int i = 0 ; i < arr.length ; i ++){
if(high < arr[i]){
low = high;
high = arr[i];
}
else if(low < arr[i]){
low = arr[i];
}
}
return low;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
sch obj = new sch();
int a = obj.sec();
System.out.println(a);
}
}
package com;
public class FindSecondHighestNumberInArray {
public static void main(String[] args) {
int []arrayOfIngeger = {-23,-989,-878,-2,-5,-3,-4,-123,-345,-98,-675,-98};
int highestNumber = arrayOfIngeger[0];
int secHighestNumber = 0;
for(int i = 1; i < arrayOfIngeger.length; i++ ) {
if(highestNumber < arrayOfIngeger[i]) {
secHighestNumber = highestNumber;
highestNumber = arrayOfIngeger[i];
}else if(secHighestNumber < arrayOfIngeger[i] && arrayOfIngeger[i] != highestNumber) {
secHighestNumber = arrayOfIngeger[i];
}
}
System.out.println("second Highest Number in Array : "+secHighestNumber);
}
}

Finding contiguous array

I am trying to get an output of [4,6,6,7] with length 4 where arr[i] <= arr[i+1] where it is non-decreasing and it is contiguous. I know what i have to do but i dont know how to do it. my code prints out [3,4,6,6,7]. I am just having trouble on the contiguous part, any help? im not allowed to use extra arrays.
public static void ascentLength(int arr[], int size) {
int length = 0;
int index = 0;
int count = 1;
for (int i = 0; i < size-1; i++) {
index = i;
if (arr[0] <= arr[i+1] && count >0) {
System.out.println(arr[i]+ " index:" + index);
length++;
count++;
}
if (arr[0] >= arr[i+1]) {
}
}
System.out.println("length: " + length);
}
/* Driver program to test above function */
public static void main(String[] args) {
int arr[] = {5, 3, 6, 4, 6, 6, 7, 5};
int n = arr.length;
ascentLength(arr, n);
}
Here is my solution, it would be easier, if you could work with List, but this works for arrays:
public static void ascentLength(int arr[], int size) {
if(size == 1) System.out.println("length: 1");
// variables keeping longest values
int longestStartingIndex = 0;
int longestLength = 1;
// variables keeping current values
int currentStartingIndex = 0;
int currentCount = 1;
for (int i = 1; i < size; i++) {
if (arr[i-1] <= arr[i]) {
currentCount++;
} else {
// check if current count is the longest
if(currentCount > longestLength) {
longestLength = currentCount;
longestStartingIndex = currentStartingIndex;
}
currentStartingIndex = i;
currentCount = 1;
}
}
if(currentCount > longestLength) {
longestLength = currentCount;
longestStartingIndex = currentStartingIndex;
}
}

ArrayList in Java that lists square numbers - Homework

I think I have most of the code figured out, there is just one part that is giving me grief. When I use printList(list) it prints out 1, 2, 3,... up to 9 when it is supposed to be printing the squares of these numbers. If I print out the createSquaresList(10) it is correctly printed. Any help is appreciated :-).
import java.util.*;
public class Lab8a
{
public static void main(String args[])
{
ArrayList<Double> list = createSquaresList(10);
printList(list);
removeElement(list, 4);
printList(list);
swapElements(list, 2, 6);
printList(list);
double max = getMaxValue(list);
double ave = getAverage(list);
System.out.println("Max Value = " + max);
System.out.println("Average = " + ave);
int idx1 = linearSearch(list, 4);
int idx2 = linearSearch(list, 75);
System.out.println("idx 1 = " + idx1);
System.out.println("idx 2 = " + idx2);
}
public static ArrayList<Double> createSquaresList(int n)
{
ArrayList<Double> squares= new ArrayList<>();
double s = 0.0;
for (double i = 0.0; i <= n-1; i++)
{
s = i*i;
squares.add(s);
}
return squares;
}
public static double getMaxValue(ArrayList<Double> list)
{
double largest = list.get(0);
for (int i = 1; i < list.size(); i++)
{
if (list.get(i) > largest)
{
largest = list.get(i);
}
}
return largest;
}
public static double getAverage(ArrayList<Double> list)
{
double avg = 0.0;
double sum = 0.0;
for (int i =0; i < list.size(); i++)
{
sum += list.get(i);
}
avg = sum / list.size();
return avg;
}
public static void removeElement(ArrayList<Double> list, double index)
{
double temp = 0.0;
int lastPos = list.size() - 1;
double last = list.get(lastPos);
index = temp;
temp = last;
last = index;
list.remove(lastPos);
}
public static void swapElements(ArrayList<Double> list, int a, int b)
{
int temp = 0;
a = temp;
temp = b;
b = a;
}
public static int linearSearch(ArrayList<Double> list, double val)
{
int pos = 0;
boolean found = false;
while (pos < list.size() && !found)
{
if (list.get(pos) == val)
{
found = true;
}
else
{
pos++;
}
}
if (found)
{
return pos;
}
else
{
return -1;
}
}
public static void printList(ArrayList<Double> list)
{
for(int i = 0; i < list.size(); i++)
{
System.out.print(i);
if(i < list.size()-1)
{
System.out.print(", ");
}
}
System.out.println("");
}
}
Change
System.out.print(i);
to
System.out.print(list.get(i));
it is because you are print the int not the contents of the list,
try changing the 3 line of the function printList to:
System.out.print(list.get(i));

PHP Function in Java

I'm trying to convert a PHP-Script to Java.
But somehow I don't get it working..
<?php
$karten = array(12, 10, 8, 14, 9, 11, 13);
for ($i = 1; $i <= count($karten); $i++) {
print_r($karten);
echo '<br>';
if ($karten[$i] > $Karten[$i - 1]) {
for ($a = 0; $a < count($karten); $a++) {
if ($karten[$a] > $karten[$i]) {
//Karten vorne dran setzen
$karte = $karten[$i];
unset($karten[$i]);
array_splice($karten, $a, 0, array($karte));
break;
}
}
}
}
?>
We have to use Eclipse in School, so not the latest version of Java
Here is what i got so far:
Main.java:
import java.util.Arrays;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
KartenAlgo ka = new KartenAlgo();
int[] stapel = new int[7];
int[] sStapel = new int[stapel.length];
stapel[0] = 12;
stapel[1] = 10;
stapel[2] = 8;
stapel[3] = 14;
stapel[4] = 9;
stapel[5] = 11;
stapel[6] = 13;
sStapel = ka.sortiereKarten(stapel);
}
}
algorithm.java:
import java.util.*;
public class KartenAlgo {
public int[] sortiereKarten(int[] array) {
int[] returnArr = new int[array.length];
for (int i = 1; i < array.length; i++) {
if (array[i] > array[i - 1]) {
for (int a = 0; a < array.length; a++) {
if (array[a] > array[i]) {
int karte = array[i];
array = this.unset(array, i);
array = this.array_insert(array, a, karte);
break;
}
}
}
}
return returnArr;
}
private int[] unset(int[] array, int index) {
int[] returnArr = new int[array.length];
for (int i = 0; i < array.length; i++) {
if (i != index) {
if (i < index) {
returnArr[i] = array[i];
} else if (i == array.length - 1) {
returnArr[i] = -1;
} else {
returnArr[i] = array[i - 1];
}
}
}
return returnArr;
}
private int[] array_insert(int[] array, int pos, int insert) {
int[] returnArr = new int[array.length];
for (int i = 0; i < returnArr.length; i++) {
if (i < pos) {
returnArr[i] = array[i];
} else if (i == pos) {
returnArr[i] = insert;
} else {
returnArr[i] = array[i - 1];
}
}
System.out.println(Arrays.toString(array));
return returnArr;
}
}
I tried to rebuild PHP's unset and a simple variant of array_splice in Java, but I dont get it working.
In PHP unset work like this:
(unset remove/delete elemen in array and you get shorter array)
private static int[] unset(int[] arrIn, int index)
{
int i;
// new array is shorter
int[] arrOut = new int[arrIn.length-1];
// copy element "before" arrIn[index]
for(i = 0; i < index ; i++) {
arrOut[i] = arrIn[i];
}
// copy element "after" arrIn[index]
for(i = index; i < arrOut.length ; i++) {
arrOut[i] = arrIn[i+1];
}
return arrOut;
}
array_insert inserts elemen into array and you get longer array.
private static int[] array_insert(int[] arrIn, int pos, int value)
{
int i;
// new array is longer
int[] arrOut = new int[arrIn.length+1];
// copy element "before" arrIn[pos]
for(i = 0; i < pos ; i++) {
arrOut[i] = arrIn[i];
}
// put element in arrOut[pos]
arrOut[pos] = value;
// copy element "from" arrIn[pos] "to" end of arrIn[]
for(i = pos; i < arrIn.length ; i++) {
arrOut[i+1] = arrIn[i];
}
return arrOut;
}

Generating permutations of an int array using java -- error

I am writing a JAVA code to generate all permutations of a integer array.
Though I am getting the number of permutations right, the permutations themselves are not correct.
On running I obtain:
Input array Length
3
1
2
3
0Permutation is
1, 2, 3,
##########################
1Permutation is
1, 3, 2,
##########################
2Permutation is
3, 1, 2,
##########################
3Permutation is
3, 2, 1,
##########################
4Permutation is
1, 2, 3,
##########################
5Permutation is
1, 3, 2,
##########################
6 number of permutations obtained
BUILD SUCCESSFUL (total time: 3 seconds)
public class PermulteArray {
public static int counter = 0;
public static void Permute(int[] input, int startindex) {
int size = input.length;
if (size == startindex + 1) {
System.out.println(counter + "Permutation is");
for (int i = 0; i < size; i++) {
System.out.print(input[i] + ", ");
}
System.out.println();
System.out.println("##########################");
counter++;
} else {
for (int i = startindex; i < size; i++) {
int temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
Permute(input, startindex + 1);
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input array Length");
int arraylength = in.nextInt();
int[] input = new int[arraylength];
for (int i = 0; i < arraylength; i++) {
input[i] = in.nextInt();
}
counter = 0;
Permute(input, 0);
System.out.println(counter + " number of permutations obtained");
}
}
int temp=input[i];
input[i]=input[startindex];
input[startindex]=temp;
Permute(input, startindex+1);
You've swapped an element before calling Permute but you need to swap it back again afterwards to keep consistent positions of elements across iterations of the for-loop.
This is the best solution I have seen so far :
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6 };
permute(0, a);
}
public static void permute(int start, int[] input) {
if (start == input.length) {
//System.out.println(input);
for (int x : input) {
System.out.print(x);
}
System.out.println("");
return;
}
for (int i = start; i < input.length; i++) {
// swapping
int temp = input[i];
input[i] = input[start];
input[start] = temp;
// swap(input[i], input[start]);
permute(start + 1, input);
// swap(input[i],input[start]);
int temp2 = input[i];
input[i] = input[start];
input[start] = temp2;
}
}
check this out
for (int i = startindex; i < input2.length; i++) {
char[] input = input2.clone();
char temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
permute(input, startindex + 1);
}
//This will give correct output
import java.util.Scanner;
public class PermulteArray {
public static int counter = 0;
public static void Permute(int[] input, int startindex) {
int size = input.length;
if (size == startindex + 1) {
System.out.println(counter + "Permutation is");
for (int i = 0; i < size; i++) {
System.out.print(input[i] + ", ");
}
System.out.println();
System.out.println("##########################");
counter++;
} else {
for (int i = startindex; i < size; i++) {
int temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
Permute(input, startindex + 1);
temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input array Length");
int arraylength = in.nextInt();
int[] input = new int[arraylength];
for (int i = 0; i < arraylength; i++) {
input[i] = in.nextInt();
}
counter = 0;
Permute(input, 0);
System.out.println(counter + " number of permutations obtained");
}
}
You can solve this using recursive calls.
https://github.com/Pratiyush/Master/blob/master/Algorithm%20Tutorial/src/arrays/Permutations.java
public void swap(int[] arr, int i, int j)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public void permute(int[] arr, int i)
{
if (i == arr.length)
{
System.out.println(Arrays.toString(arr));
return;
}
for (int j = i; j < arr.length; j++)
{
swap(arr, i, j);
permute(arr, i + 1); // recurse call
swap(arr, i, j); // backtracking
}
}
public static void main(String[] args) {
Permutations permutations = new Permutations();
int[] arr = {1, 2, 3,4};
permutations.permute(arr, 0);
}
Also, other approaches are available in
http://www.programcreek.com/2013/02/leetcode-permutations-java/
http://www.programcreek.com/2013/02/leetcode-permutations-ii-java/
public class PermuteArray {
public static void permute(char[] input2, int startindex) {
if (input2.length == startindex) {
displayArray(input2);
} else {
for (int i = startindex; i < input2.length; i++) {
char[] input = input2.clone();
char temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
permute(input, startindex + 1);
}
}
}
private static void displayArray(char[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + "; ");
}
System.out.println();
}
public static void main(String[] args) {
char[] input = { 'a', 'b', 'c', 'd'};
permute(input, 0);
}
}
import java.util.ArrayList;
public class RecursivePermGen {
void permGen(int n, int m, ArrayList<Integer> cur) {
if(m == 0) {
System.out.println(cur);
return;
}
for(int i = 1; i <= n; i++) {
cur.add(0, i);
permGen(n, m-1, cur);
cur.remove(0);
}
}
public static void main(String[] args) {
RecursivePermGen pg = new RecursivePermGen();
ArrayList<Integer> cur = new ArrayList<Integer>();
pg.permGen(2, 2, cur);
}
}
I have simple answer for this question, you can try with this.
public class PermutationOfString {
public static void main(String[] args) {
permutation("123");
}
private static void permutation(String string) {
printPermutation(string, "");
}
private static void printPermutation(String string, String permutation) {
if (string.length() == 0) {
System.out.println(permutation);
return;
}
for (int i = 0; i < string.length(); i++) {
char toAppendToPermutation = string.charAt(i);
String remaining = string.substring(0, i) + string.substring(i + 1);
printPermutation(remaining, permutation + toAppendToPermutation);
}
}
}
A solution i have used several times (mostly for testing purposes) is in the following gist. It is based on the well-known algorithm to generate permutations in lexicographic order (no recursion):
/**
* Compute next (in lexicographic order) permutation and advance to it.
*
* Find greater index i for which a j exists, such that:
* j > i and a[i] < a[j] (i.e. the 1st non-inversion).
* For those j satisfying the above, we pick the greatest.
* The next permutation is provided by swapping
* items at i,j and reversing the range a[i+1..n]
*/
void advanceToNext() {
// The array `current` is the permutation we start from
// Find i when 1st non-inversion happens
int i = n - 2;
while (i >= 0 && current[i] >= current[i + 1])
--i;
if (i < 0) {
// No next permutation exists (current is fully reversed)
current = null;
return;
}
// Find greater j for given i for 1st non-inversion
int j = n - 1;
while (current[j] <= current[i])
--j;
// Note: The range a[i+1..n] (after swap) is reverse sorted
swap(current, i, j); // swap current[i] <-> current[j]
reverse(current, i + 1, n); // reverse range [i+1..n]
}
A complete solution (in the form of a class) lies here:
https://gist.github.com/drmalex07/345339117fef6ca47ca97add4175011f

Categories