I have created my version of the merge sort algorithm in java code. My issues are these: when I run the code as is, I get a NullPointerExecpetion in the main on line 27 (see commented line). And I know there is way to make the method calls and instantiate newArray without them being static but Im not quite sure how.. can someone help fix these? I am still relatively new to java so be nice :)
Main:
import java.util.Random;
public class MergeSort_main
{
public static void main(String[] args)
{
int[] originalArray = new int[1000];
Random rand = new Random();
for (int i = 0; i < originalArray.length; i++)
{
int randNum = rand.nextInt(1000)+1;
originalArray[i] = randNum;
}
for(int i = 0; i < originalArray.length; i++)
{
System.out.println(i+"." + originalArray[i]);
}
System.out.println("---------------------End Random Array-------\n");
MergeSortAlgorithm.mergeSortAlg(originalArray);
int[] sortedArray = MergeSortAlgorithm.getSortedArray();
for(int i = 0; i < sortedArray.length; i++) //NULL POINTER EXCEPTION HERE
{
System.out.println(i+ "." + sortedArray[i]);
}
}
}
Algorithm Class:
public class MergeSortAlgorithm
{
private static int[] newArray;
public static void mergeSortAlg(int[] randomNums)
{
int size = randomNums.length;
if (size < 2)
{
return; //if the array can not be split up further, stop attempting to split.
}
int half = size / 2;
int firstHalfNums = half;
int secondHalfNums = size - half;
int[] firstArray = new int[firstHalfNums];
int[] secondArray = new int[secondHalfNums];
for (int i = 0; i < half; i++)
{
firstArray[i] = randomNums[i];
}
for (int i = half; i < size; i++)
{
secondArray[i - half] = randomNums[i];
}
mergeSortAlg(firstArray);
mergeSortAlg(secondArray);
merge(firstArray, secondArray, randomNums);
}
public static void merge(int[] firstArray, int[] secondArray, int[] newArray)
{
int firstHalfNums = firstArray.length;
int secondHalfNums = secondArray.length;
int i = 0; //iterator for firstArray
int j = 0; //iterator for second array
int k = 0; //interator for randomNums array
while (i < firstHalfNums && j < secondHalfNums)
{
if (firstArray[i] <= secondArray[j])
{
newArray[k] = firstArray[i];
i++;
k++;
}
else
{
newArray[k] = secondArray[j];
k++;
j++;
}
}
while (i < firstHalfNums)
{
newArray[k] = firstArray[i];
k++;
i++;
}
while (j < firstHalfNums)
{
newArray[k] = secondArray[j];
k++;
j++;
}
}
public static int[] getSortedArray()
{
return newArray;
}
}
Basically, the only problem with your code is that you don't initialize newArray with any values, resulting in a null.
You are also redefining newArray at the top of your merge function .
The problem is that newArray[] is never instantiated i.e. newArray reference is pointing to null. And, no change is made in the newArray so value or reference returned to main is null. And, then you are performing sortedArray.length where sorted array having a null value.
You have to make newArray[] point to randomNums[].
Related
Hello I am having difficulty implementing a counting sort method in java. I believe the problem comes from the last two loops I have in the method. I am getting an ArrayIndexOutOfBounds exception : 8. I believe this comes from my second to last for loop when at index 5 the value is 8 but I am not sure how to resolve this. Any help is appreciated. Thank you!
In my code k is the highest value in the input array.
Code:
public static void main(String[] args) {
int [] arrayOne = {0,1,1,3,4,5,3,0};
int [] output = Arrays.copyOf(arrayOne, arrayOne.length);
System.out.println(Arrays.toString(arrayOne));
countingSort(arrayOne, output, 5);
System.out.println(Arrays.toString(output));
}
public static void countingSort(int[] input, int[] output , int k){
int [] temp = Arrays.copyOf(input, k+1);
for (int i = 0; i <= k; i++){
temp[i] = 0;
}
for (int j = 0; j <= input.length - 1; j++){
temp[input[j]] = temp[input[j]] + 1;
}
for (int i = 1; i <= k; i++){
temp[i] = temp[i] + temp[i-1];
}
for (int j = input.length; j >= 1; j--){
output[temp[input[j]]] = input[j];
temp[input[j]] = temp[input[j]] - 1;
}
}
The problem is in the first loop because the array temp lenght is 6 and you are doing 7 interations in there.
So at the end of the for it is trying to do temp[6]=0 and the last position of your array is temp[5].
To fix this change your first loop to:
for (int i = 0; i < k; i++){
In the last loop you will get the same exception cause input[8] doesn't exist.
import java.util.Arrays;
public class CountingSort {
public static void main(String[] args) {
int[] input = {0,1,1,3,4,5,3,0};
int[] output = new int[input.length];
int k = 5; // k is the largest number in the input array
System.out.println("before sorting:");
System.out.println(Arrays.toString(input));
output = countingSort(input, output, k);
System.out.println("after sorting:");
System.out.println(Arrays.toString(output));
}
public static int[] countingSort(int[] input, int[] output, int k) {
int counter[] = new int[k + 1];
for (int i : input) { counter[i]++; }
int ndx = 0;
for (int i = 0; i < counter.length; i++) {
while (0 < counter[i]) {
output[ndx++] = i;
counter[i]--;
}
}
return output;
}
}
Above code is adapted from: http://www.java67.com/2017/06/counting-sort-in-java-example.html
this may help but try using the Arraya.sort() method.
e.g:
//A Java program to sort an array of integers in ascending order.
// A sample Java program to sort an array of integers
// using Arrays.sort(). It by default sorts in
// ascending order
import java.util.Arrays;
public class SortExample
{
public static void main(String[] args)
{
// Our arr contains 8 elements
int[] arr = {13, 7, 6, 45, 21, 9, 101, 102};
Arrays.sort(arr);
System.out.printf("Modified arr[] : %s",
Arrays.toString(arr));
}
}
example is a snippet from https://www.geeksforgeeks.org/arrays-sort-in-java-with-examples/
As per algorithm following implementation, I have prepared for the count sort technique
public static int[] countSort(int elements[]) {
int[] sorted = new int[elements.length+1];
int[] range = new int[getMax(elements)+1];
for(int i=0;i<range.length;i++) {
range[i] = getCount(i, elements);
try {
range[i] = range[i]+range[i-1];
}catch(ArrayIndexOutOfBoundsException ae) {
continue;
}
}
for(int i=0;i<elements.length;i++) {
sorted[range[elements[i]]] = elements[i];
range[elements[i]] = range[elements[i]]-1;
}
return sorted;
}
public static int getCount(int value,int[] elements) {
int count = 0;
for(int element:elements) {
if(element==value) count++;
}
return count;
}
public static int getMax(int elements[]) {
int max = elements[0];
for(int i=0;i<elements.length;i++) {
if(max<elements[i]) {
max = elements[i];
}
}
return max;
}
Please review and let me know if any feedback and it is more helpful.
Note :
Non-negative no won't support in the above implementation.
don't use 0th index of the sorted array.
For school, i have to build myself a method in java that compresses an array using RLE(run-length encoding). I can't find a solution online because my teacher wants me to solve the problem myself. I, unfortunately, cannot do this for i am a busy man with some busy plans.
RLE turns this: {1,1,1,1,2,2,3,3,6,6,6,7,8,8,8}
into this: {4,1,2,2,2,3,3,6,1,7,3,8}
it basically makes a new array that follows this formula {# of this value, this value, # of this value, this value, cont...} there are 4 1's so {4,1} you get my drift.
Here is what i tried to do(forgive me for my crappy code, i am merely a high school student):
public class tester{
public static void main(String[] args){
int[] potato = {1,1,1,2,2,4,4,4,6,6,6,6};
printArray(compress(potato));
}
public static void printArray(int[] arr){
for(int i = 0; i < arr.length; i++){
System.out.println(arr[i]);
}
}
public static int[] compress(int[] a) {
//figure out how many different numbers there are.
int diffNums = 1;
for(int i = 0; i < a.length; i++){
if(i != a.length-1 && a[i] != a[i+1]){
diffNums++;
}
}
//make compressed array at the correct length.
int[] compressed = new int[diffNums * 2];
//figure out what each number is.
int[] nums = new int[diffNums];
nums[0] = a[0];
int spot = 0;
for(int i = 0; i < a.length; i++){
if(i != a.length-1 && a[i] != a[i+1]){
nums[spot] = a[i+1];
}
}
//figure out quantity of each number.
int[] quantities = new int[diffNums];
int spot2 = 0;
int spotcur = 0;
for(int i = 0; i < diffNums; i++){
int quant = 0;
while(a[spotcur] == a[spot2]){
quant++;
spotcur++;
}
spot2 = spotcur;
quantities[i] = quant;
}
//add them together and return compressed array
int spotter = 0;
for(int i = 0; i < diffNums; i++){
compressed[spotter] = quantities[i];
spotter++;
compressed[spotter] = nums[i];
spotter++;
}
return compressed;
}
}
Does anyone know how i can fix this crappy code? i am stuck on it
I think this problem could be solved with a lot less code. You could use an outer/inner loop construct something like the following:
public static int[] compress(int[] a) {
List<Integer> encoded = new ArrayList<>();
for (int i=0; i<a.length; i++) {
int num = a[i];
int count = 1;
for (int j=i+1; j<a.length; j++) {
int nextNum = a[j];
if (nextNum != num)
break;
count++;
i++;
}
encoded.add(count);
encoded.add(num);
}
return encoded.stream().mapToInt(i->i).toArray();
}
Also, the Arrays class contains a useful toString method already defined.
System.out.println(Arrays.toString(compress(potato)));
I have a 2D array , iam trying to calculate the minimum value for each column and put the result in the result array.
the code bellow is calculating the minimum value for each row , how can i get the min value for each column.
import java.util.*;
class Test20 {
public static void main ( String [] args) {
int[][] array = {{6,3,9},
{0,8,2},
{3,7,5}};
Test20 test = new Test20();
System.out.print(Arrays.toString(test.mincol(array)));
}
public static int[] mincol (int[][] n) {
int[] result = new int[n.length];
for (int i = 0; i < n.length; i++) {
int min = n[0][i];
for (int j = 0; j < n[0].length; j++) {
if (n[j][i] < min) {
min = n[j][i];
}
}
result[i] = min;
}
return result;
}
}
Just change the loop the following way:
min = 0;
for(int i=0;i<n.length;i++){
for(int j=0;j<n[0].length;j++){
if(n[j][i]<n[j][min]){
min=j;
}
result[i]=n[min][i];
}
Be aware that you instantiate your result array by the length of the first dimension in your array but later use the n[][] param for looping and access the length of the second dimension in your loop.
If your two dim array is for example 4x5, this will cause ArrayOutOfBoundsExceptions.
You only need to do the same thing but inverting the variables
for(int i=0;i<n.length;i++){
for(int j=0;j<n[0].length;j++){
if(n[j][i]<n[min][j]){
min=i;
}
result[j]=n[min][j];
}
}
If your code is correct just change:
if(n[i][j]<n[i][min]){
min=j;
}
with
if(n[i][j]<n[result[i]][j]){
result[i]=i;
}
finally
for(int i=0;i<n.length;i++) result[i]=n[result[i][j];
you don't need min. But change
int [] result = new int[n.length];
to
int [] result = new int[n[0].length];
How about you transpose your two dimensional array like:
public static int[][] transpose (int[][] original) {
int[][] array = new int[original.length][];
// transpose
if (original.length > 0) {
for (int i = 0; i < original[0].length; i++) {
array[i] = new int[original[i].length];
for (int j = 0; j < original.length; j++) {
array[i][j] = original[j][i];
}
}
}
return array;
}
and then call it as:
System.out.print(Arrays.toString(test.minrow(transpose(array))));
Or, if you want to go without transpose, this is how you can do:
public static int[] mincol (int[][] n) {
int[] result = new int[n.length];
for (int i = 0; i < n.length; i++) {
int min = n[0][i];
for (int j = 0; j < n[0].length; j++) {
if (n[j][i] < min) {
min = n[j][i];
}
}
result[i] = min;
}
return result;
}
Your for loop looks ok. Check the code below I fixed some minor issues.
Based on your code replace Class code with below:
public class Test {
public static void main(String[] args) {
int[][]array={{6,1,9}, {0,1,2}, {3,7,5}};
int[] test;
test = minrow(array);
for(int i=0; i<test.length; i++){
System.out.println(test[i]);
}
}
public static int[] minrow(int[][] n){
int [] result = new int[n.length];
int min;
for(int i=0;i<n.length;i++){
min=0;
for(int j=0;j<n[i].length;j++){
if(n[i][j]<n[i][min]){
min=j;
}
}
result[i]=n[i][min];
}
return result;
}
}
I am trying to measure the time it takes for my system to sort an Array of 50 thousand random numbers using Selection sort, however i am getting an error. The error i received is null pointed exception.
Would someone look at where i am going wrong here
import java.util.Random;
public class SelectionSort {
public static void main(String[] args) {
int arrayOne[] = null;
int arr[] = { 9, 1, 8, 5, 7, -1, 6, 0, 2, 2718 };
int arr1[] = fillArray(arrayOne);
int sortedArr[] = selectionSort(arr1);
System.out.println("Selection sort implemented below");
System.currentTimeMillis();
long start = System.currentTimeMillis();
print(sortedArr);
long elapsed = System.currentTimeMillis() - start;
System.out.println(elapsed);
}
private static int[] fillArray(int[] array) {
Random generator2 = new Random(System.currentTimeMillis());
for (int x = 0; x < 50000; x++) {
array[x] = generator2.nextInt();
}
return array;
}
private static int[] selectionSort(int[] arr) {
int minIndex, tmp;
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
minIndex = i;
for (int j = i + 1; j < n; j++)
if (arr[j] < arr[minIndex])
minIndex = j;
if (minIndex != i) {
tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
}
return arr;
}
private static void print(int[] Array) {
// TODO prints the array
for (int i = 0; i < Array.length; i++)
System.out.print(Array[i] + " ");
System.out.println();
}
}
You're trying to fill arrayOne which is null:
int arrayOne[] = null;
You need to initialize it with sufficient capacity before you try to fill it:
int arrayOne[] = new int[50000];
When you call fillArray(arrayOne) you are passing null as the parameter. Then in the fillArray method, you are trying to put values into a null array.
By the way, if you had run through the code line by line in a debugger, you would have spotted this problem in seconds. In fact, even the exception thrown would have told you exactly which line had the problem.
Find the first covering prefix of a given array.
A non-empty zero-indexed array A consisting of N integers is given. The first covering
prefix of array A is the smallest integer P such that and such that every value that
occurs in array A also occurs in sequence.
For example, the first covering prefix of array A with
A[0]=2, A[1]=2, A[2]=1, A[3]=0, A[4]=1 is 3, because sequence A[0],
A[1], A[2], A[3] equal to 2, 2, 1, 0 contains all values that occur in
array A.
My solution is
int ps ( int[] A )
{
int largestvalue=0;
int index=0;
for(each element in Array){
if(A[i]>largestvalue)
{
largestvalue=A[i];
index=i;
}
}
for(each element in Array)
{
if(A[i]==index)
index=i;
}
return index;
}
But this only works for this input, this is not a generalized solution.
Got 100% with the below.
public int ps (int[] a)
{
var length = a.Length;
var temp = new HashSet<int>();
var result = 0;
for (int i=0; i<length; i++)
{
if (!temp.Contains(a[i]))
{
temp.Add(a[i]);
result = i;
}
}
return result;
}
I would do this
int coveringPrefixIndex(final int[] arr) {
Map<Integer,Integer> indexes = new HashMap<Integer,Integer>();
// start from the back
for(int i = arr.length - 1; i >= 0; i--) {
indexes.put(arr[i],i);
}
// now find the highest value in the map
int highestIndex = 0;
for(Integer i : indexes.values()) {
if(highestIndex < i.intValue()) highestIndex = i.intValue();
}
return highestIndex;
}
Your question is from Alpha 2010 Start Challenge of Codility platform. And here is my solution which got score of 100. The idea is simple, I track an array of counters for the input array. Traversing the input array backwards, decrement the respective counter, if that counter becomes zero it means we have found the first covering prefix.
public static int solution(int[] A) {
int size = A.length;
int[] counters = new int[size];
for (int a : A)
counters[a]++;
for (int i = size - 1; i >= 0; i--) {
if (--counters[A[i]] == 0)
return i;
}
return 0;
}
here's my solution in C#:
public static int CoveringPrefix(int[] Array1)
{
// Step 1. Get length of Array1
int Array1Length = 0;
foreach (int i in Array1) Array1Length++;
// Step 2. Create a second array with the highest value of the first array as its length
int highestNum = 0;
for (int i = 0; i < Array1Length; i++)
{
if (Array1[i] > highestNum) highestNum = Array1[i];
}
highestNum++; // Make array compatible for our operation
int[] Array2 = new int[highestNum];
for (int i = 0; i < highestNum; i++) Array2[i] = 0; // Fill values with zeros
// Step 3. Final operation will determine unique values in Array1 and return the index of the highest unique value
int highestIndex = 0;
for (int i = 0; i < Array1Length; i++)
{
if (Array2[Array1[i]] < 1)
{
Array2[Array1[i]]++;
highestIndex = i;
}
}
return highestIndex;
}
100p
public static int ps(int[] a) {
Set<Integer> temp = new HashSet<Integer>();
int p = 0;
for (int i = 0; i < a.length; i++) {
if (temp.add(a[i])) {
p = i+1;
}
}
return p;
}
You can try this solution as well
import java.util.HashSet;
import java.util.Set;
class Solution {
public int ps ( int[] A ) {
Set set = new HashSet();
int index =-1;
for(int i=0;i<A.length;i++){
if(set.contains(A[i])){
if(index==-1)
index = i;
}else{
index = i;
set.add(A[i]);
}
}
return index;
}
}
Without using any Collection:
search the index of the first occurrence of each element,
the prefix is the maximum of that index. Do it backwards to finish early:
private static int prefix(int[] array) {
int max = -1;
int i = array.length - 1;
while (i > max) {
for (int j = 0; j <= i; j++) { // include i
if (array[i] == array[j]) {
if (j > max) {
max = j;
}
break;
}
}
i--;
}
return max;
}
// TEST
private static void test(int... array) {
int prefix = prefix(array);
int[] segment = Arrays.copyOf(array, prefix+1);
System.out.printf("%s = %d = %s%n", Arrays.toString(array), prefix, Arrays.toString(segment));
}
public static void main(String[] args) {
test(2, 2, 1, 0, 1);
test(2, 2, 1, 0, 4);
test(2, 0, 1, 0, 1, 2);
test(1, 1, 1);
test(1, 2, 3);
test(4);
test(); // empty array
}
This is what I tried first. I got 24%
public int ps ( int[] A ) {
int n = A.length, i = 0, r = 0,j = 0;
for (i=0;i<n;i++) {
for (j=0;j<n;j++) {
if ((long) A[i] == (long) A[j]) {
r += 1;
}
if (r == n) return i;
}
}
return -1;
}
//method must be public for codility to access
public int solution(int A[]){
Set<Integer> set = new HashSet<Integer>(A.length);
int index= A[0];
for (int i = 0; i < A.length; i++) {
if( set.contains(A[i])) continue;
index = i;
set.add(A[i]);
}
return index;
}
this got 100%, however detected time was O(N * log N) due to the HashSet.
your solutions without hashsets i don't really follow...
shortest code possible in java:
public static int solution(int A[]){
Set<Integer> set = new HashSet<Integer>(A.length);//avoid resizing
int index= -1; //value does not matter;
for (int i = 0; i < A.length; i++)
if( !set.contains(A[i])) set.add(A[index = i]); //assignment + eval
return index;
}
I got 100% with this one:
public int solution (int A[]){
int index = -1;
boolean found[] = new boolean[A.length];
for (int i = 0; i < A.length; i++)
if (!found [A[i]] ){
index = i;
found [A[i]] = true;
}
return index;
}
I used a boolean array which keeps track of the read elements.
This is what I did in Java to achieve 100% correctness and 81% performance, using a list to store and compare the values with.
It wasn't quick enough to pass random_n_log_100000 random_n_10000 or random_n_100000 tests, but it is a correct answer.
public int solution(int[] A) {
int N = A.length;
ArrayList<Integer> temp = new ArrayList<Integer>();
for(int i=0; i<N; i++){
if(!temp.contains(A[i])){
temp.add(A[i]);
}
}
for(int j=0; j<N; j++){
if(temp.contains(A[j])){
temp.remove((Object)A[j]);
}
if(temp.isEmpty()){
return j;
}
}
return -1;
}
Correctness and Performance: 100%:
import java.util.HashMap;
class Solution {
public int solution(int[] inputArray)
{
int covering;
int[] A = inputArray;
int N = A.length;
HashMap<Integer, Integer> map = new HashMap<>();
covering = 0;
for (int i = 0; i < N; i++)
{
if (map.get(A[i]) == null)
{
map.put(A[i], A[i]);
covering = i;
}
}
return covering;
}
}
Here is my Objective-C Solution to PrefixSet from Codility. 100% correctness and performance.
What can be changed to make it even more efficient? (without out using c code).
HOW IT WORKS:
Everytime I come across a number in the array I check to see if I have added it to the dictionary yet.
If it is in the dictionary then I know it is not a new number so not important in relation to the problem. If it is a new number that we haven't come across already, then I need to update the indexOftheLastPrefix to this array position and add it to the dictionary as a key.
It only used one for loop so takes just one pass. Objective-c code is quiet heavy so would like to hear of any tweaks to make this go faster. It did get 100% for performance though.
int solution(NSMutableArray *A)
{
NSUInteger arraySize = [A count];
NSUInteger indexOflastPrefix=0;
NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];
for (int i=0; i<arraySize; i++)
{
if ([myDict objectForKey:[[A objectAtIndex:i]stringValue]])
{
}
else
{
[myDict setValue:#"YES" forKey:[[A objectAtIndex:i]stringValue]];
indexOflastPrefix = i;
}
}
return indexOflastPrefix;
}
int solution(vector &A) {
// write your code in C++11 (g++ 4.8.2)
int max = 0, min = -1;
int maxindex =0,minindex = 0;
min = max =A[0];
for(unsigned int i=1;i<A.size();i++)
{
if(max < A[i] )
{
max = A[i];
maxindex =i;
}
if(min > A[i])
{
min =A[i];
minindex = i;
}
}
if(maxindex > minindex)
return maxindex;
else
return minindex;
}
fwiw: Also gets 100% on codility and it's easy to understand with only one HashMap
public static int solution(int[] A) {
// write your code in Java SE 8
int firstCoveringPrefix = 0;
//HashMap stores unique keys
HashMap hm = new HashMap();
for(int i = 0; i < A.length; i++){
if(!hm.containsKey(A[i])){
hm.put( A[i] , i );
firstCoveringPrefix = i;
}
}
return firstCoveringPrefix;
}
I was looking for the this answer in JavaScript but didn't find it so I convert the Java answer to javascript and got 93%
function solution(A) {
result=0;
temp = [];
for(i=0;i<A.length;i++){
if (!temp.includes(A[i])){
temp.push(A[i]);
result=i;
}
}
return result;
}
// you can also use imports, for example:
import java.util.*;
// you can use System.out.println for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int[] A) {
// write your code in Java SE 8
Set<Integer> s = new HashSet<Integer>();
int index = 0;
for (int i = 0; i < A.length; i++) {
if (!s.contains(A[i])) {
s.add(A[i]);
index = i;
}
}
return index;
}
}