Data contiguity in an array in Java - java

I'm trying to see if any series of data, beginning at array position 0, is contiguous in the sense that array[0] has a numerical value of 0, array[1] has a numerical value of 1, and so on. For example:
private void isContiguous(int[] array, int position){
for(int i = 1; i < array.length; i ++){
if(!array[i].equals(null)){
long previous = this.extract_long(array[i - 1], OFFSET);
long current = this.extract_long(array[i], OFFSET);
if((previousOffset/PACKET_LENGTH) < ){
}
}
}
}
is about as far as I can think of for a general solution. This is kinda bending my mind so it'd be nice to have some help :)

Something to start with:
public static boolean isContiguous(int[] array) {
for (int i = 0; i < array.length-1; i++) {
if (array[i+1]-array[i] != 1) {
return false;
}
}
return true;
}
(I don't know why you need position, OFFSET, and so on, but the above code should fulfill the written requirement)

First of all you if you are storing primitive int in your array, they can never have a null value! The array itself might be null, but the values cannot!
Secondly if all you want to check is if array[0]==0, array[1]==1, array[2]==2 then your code should be as simple as this:
private boolean isContiguous(int []array) {
if( array == null ) return false;//a null array cannot be contiguous as it doesn't contain any elements!
for( int i = 0; i < array.length; i++ )
if( array[i] != i ) return false;
return true;
}
Would this not work?

Related

How to return value when there's no input in array method?

So, I have to write a program that counts the most repeated number in an array (e.g. 1, 2, 2, 3, 3, 3) and then tells the user what number is it (3). Finally, an online compiler tests my code and sees if my output is correct.
Here are the inputs from the program.
My issue is the last input, which is nothing. I tried to return a value but I couldn't.
Here's my code excluding the main method (Java):
Edit: Thank you everyone. I'm an idiot.
public int lengthOfLongestRun(int[] values) {
if (values == null){
return 0;
}
int lastVal = values[0];
int currentLength = 1;
int longestLength = 1;
for (int i = 1; i < values.length; i++) {
if (values[i] == lastVal)
currentLength++;
else
currentLength = 1;
lastVal = values[i];
if (currentLength > longestLength)
longestLength = currentLength;
}
return longestLength;
}
Since the array is empty you need to check the length and return zero if the length of the array is zero.
Right now you have added a condition already for null check. Just extend that and add another condition for empty array aswell.
public int lengthOfLongestRun(int[] values)
{
if(values == null || values.length == 0){ // code added here
return 0;
}
int...
...
That should solve your problem.
I can see another potential bug here. Your loop starting at position 1
for (int i = 1; i < values.length; i++)
{
What if the biggest number lies at position 1 ? You are not seeing the bug because all your input arrays starting with value 1.
You should check array size
if(values == null || array.length == 0){
return 0;
}
if(values == null || values.length == 0){
return 0;
}
If the input array is [], its length is zero. So just check for that:
if (values.length == 0) {
return 0;
}
Note that it's maybe better not to return 0 in the null case: it's an invalid input, so don't give a valid output. Throw a NullPointerException or IllegalArgumentException, for instance.
You can also write the loop so as not to need to handle the zero case separately:
int longestLength = 0;
int i = 0;
while (i < values.length) {
int start = i++;
while (i < values.length && values[i] == values[start]) {
++i;
}
longestLength = Math.max(longestLength, i - start);
}
return longestLength;

Codility PermCheck Solution isn't working on a few data sets

Trying to solve codility lessons for practice and working on this.
Written my code in Java and tested the code on a wide range of inputs, however the code fails for extreme_min_max, single and double in the codility test results.
Assumption given:
N is an integer within the range [1..100,000].
Each element of array A is an integer within the range [1..1,000,000,000].
Explanation of my code:
1. Sort the given array.
2. Iterate over each element in the array to find the difference between every consecutive pair. If the difference is not 1, Then its not a perm hence return 0. In case there is only one element in the array, return 1.
Can anyone please help me find out the bug(s) in my code?
My code:
public int solution(int[] A)
{
if(A.length == 1)
return 1;
Arrays.sort(A);
for (int i = 0; i < A.length-1; i++)
{
long diff = Math.abs(A[i] - A[i+1]);
if(diff!=1)
return 0;
}
return 1;
}
Here is simple and better implementation which runs in O(N) time complexity and takes O(N) space complexity.
public int solution(int[] A)
{
int size = A.length;
int hashArray[] = new int[size+1];
for (int i = 0; i < size; i++)
{
if(A[i]>size)
return 0;
else
hashArray[A[i]]+=1;
}
for(int i=1;i<=size;i++)
if(hashArray[i]!=1)
return 0;
return 1;
}
Try this in C# (Score 100%) :
using System;
using System.Linq;
class Solution {
public int solution(int[] A) {
if (A.Any(x => x == 0)) { return 0; }
var orderSelect = A.OrderBy(x => x).GroupBy(x => x);
if (orderSelect.Any(x => x.Count() > 1)) { return 0; }
var res = Enumerable.Range(1, A.Length).Except(A);
return res.Any() ? 0 : 1;
}
}
Pretty simple:
Your code doesn't check this condition:
A permutation is a sequence containing each element from 1 to N once, and only once.
Ensure that the first element after sorting is 1, and everything should work.
I'm not big on Java syntax, but what you want to do here is:
Create an array temp the length of A - initialized to 0.
Go over A and do temp[A[i]]++.
Go over temp, and if any place in the array is not 1, return false.
If duplicate exists - return 0 I have implemented with 100% pass
https://codility.com/demo/results/trainingWX2E92-ASF/
public static int permCheck(int A[]){
Set<Integer> bucket = new HashSet<Integer>();
int max = 0;
int sum=0;
for(int counter=0; counter<A.length; counter++){
if(max<A[counter]) max=A[counter];
if(bucket.add(A[counter])){
sum=sum+A[counter];
}
else{
return 0;
}
}
System.out.println(max+"->"+sum);
int expectedSum = (max*(max+1))/2;
if(expectedSum==sum)return 1;
return 0;
}
Here's my first 100% code.
I can't say if it's the fastest but it seems all correct -- watch the double OR ( || ) condition.
import java.util.Arrays;
class Solution
{
public int solution(int[] A)
{
int i = 0;
int size = A.length;
if ( size > 0 && size < 100001)
{
// Sort the array ascending:
Arrays.sort(A);
// Check each element:
for(i = 0; i < size; i++)
if ( A[i] > size || A[i] != (i + 1) )
return 0;
return 1;
}
return 0;
}
}
EDIT
Actually, we need not worry about valid first element data (i.e. A[i] > 0) because, after sorting, a valid perm array must have A[0] = 1 and this is already covered by the condition A[i] = i + 1.
The upper limit for array entries (> 1,000,000,000) is restricted further by the limit on the array size itself (100,000) and we must check for conformity here as there will be a Codility test for this. So I have removed the lower limit condition on array entries.
Below code runs and gave me a 100%, the time complexity is O(n):
private static int solution(int[] A) {
int isPermutation = 1; // all permutations start at 1
int n = A.length;
Arrays.sort(A);
if (n == 0) return 0; // takes care of edge case where an empty array is passed
for (int i = 0; i < n; i++) {
if (A[i] != isPermutation) { //if current array item is not equals to permutation, return 0;
return 0;
}
isPermutation++;
}
return 1;
}
100% score with complexity O(N)
public int solution(int[] A) {
int res = 1;
if (A.length == 1 && A[0]!=1)
return 0;
int[] B = new int[A.length];
for (int j : A) {
int p = j - 1;
if (A.length > p)
B[p] = j;
}
for (int i = 0; i < B.length - 1; i++) {
if (B[i] + 1 != B[i + 1]) {
res = 0;
break;
}
}
return res;
}

Shifting and Re-organizing Arrays

I have an array, let's say: LRU_frame[] = {4,1,0,3}
I have a random() function that spits out a random number. If the random number n is contained in the array LRU_frame, then, n should be on LRU_frame[0] and everything else must be shifted down accordingly.
For example if random() gives me a 0, the new LRU_frame[] = {0,4,1,3}
Another example, if random() gives me a 3, the new LRU_frame[] = {3,4,1,0}
How do I do this for any Array size with any number of elements in it?
I know how to shift arrays by adding a new element on LRU_frame[0] but have no idea on how to re-organize the array like I need.
This is the code I have so far and let's assume char a is the random number(casted into char) to use and re-organize the array.
public static void LRU_shiftPageRef(char a) {
for (int i = (LRU_frame.length - 2); i >= 0; i--) {
LRU_frame[i + 1] = LRU_frame[i];
}
LRU_frame[0] = a;
}
You have a good idea, you only need to find the position of the a element in the array and start the cycle from it, instead of LRU_frame.length.
int index = -1;
// find the positon of 'a' in the array
for (int i = 0; i <= (LRU_frame.length - 1); i++) {
if (LRU_frame[i] == a) {
index = i;
break;
}
}
// if it is present, do roughly the same thing as before
if (index > -1) {
for (int i = (index - 1); i >= 0; i--) {
LRU_frame[i + 1] = LRU_frame[i];
}
LRU_frame[0] = a;
}
However if you can use ArrayLists it gets much easier.
// declaration
ArrayList<Integer> LRU_frame = new ArrayList<Integer>();
...
if (LRU_frame.contains(a)) {
LRU_frame.remove((Integer) a);
LRU_frame.add(0, a);
}
I think this could be the sort of thing you are after:
public static void LRU_shiftPageRef(char a) {
int index = indexOf(a);
if (index == -1) {
//not currently in array so create a new array 1 bigger than existing with a in newArray[0] or ignore depending on functionality required.
} else if (index > 0) {
//Set first entry as a and shift existing entries right
char insertChar = a;
char nextChar = LRU_frame[0];
for (int i =0; i < index; i++) {
LRU_frame[i] = insertChar;
insertChar = nextChar;
nextChar = LRU_frame[i+1];
}
LRU_frame[index] = insertChar;
} else {
//do nothing a is already at first position
}
}
public static int indexOf(char a) {
for (int i=0; i < LRU_frame.length; i++) {
if (LRU_frame[i] == a) {
return i;
}
}
return -1;
}
Use Arrays.sort(LRU_frame); to sort the entire array, or Arrays.sort(LRU_frame, fromIndex, toIndex)); to sort part of the array.
Arrays class has other useful methods like copyOfRange.

Comparing index 0 in array with all other indexes

If I want to compare index 0 with index 1, 2 and 3 for instance, how is that possible?
boolean iftrue = false;
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < i; j++) {
if (IntValue(array[j]) == IntValue(array[i + j])) {
iftrue = true;
}
}
}
return iftrue;
}
Just to put Sotirios' suggestion into code... Recall he suggested you save the first elem and compare other elements against it.
public boolean sameAsFirstElem(int[] array) {
boolean isEqual = false;
int firstElem = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] == firstElem) {
return true;
}
}
return isEqual;
}
Take 0th element is an variable and go on searching from 1st index onward. If you find the match stop else go all the way upto end of the array and report that match not found. This can be done in linear time O(N) where N is the size of the array. No need to have two loops and hence increase the time complexity to O(N^2)
boolean sameAsFirstElem(Object[] array) {
boolean isEqual = false; //Assume match will not be there, if we come across any,
// we will set it to true
int firstElement = IntValue(array[0]);
for (int i = 1; i < array.length; i++) {
if (IntValue(array[i]) == firstElement) {
isEqual = true; //Indicating that match has found
}
}
return isEqual;
}
I am assuming that IntValue(Object) return int, and hence the int firstElement, and taking Object as a parameter.

Java logic issues

I'm working on a method that finds the first instance of a given value and returns its position. It works for some cases, but if I give it an array of [1,2,3], and set the value to 2, it returns 0, instead of 1. I'm not sure why, either. Here is the code:
int b = 0;
for(int a = 0; a < values.length; a++) {
if (values[a] == find){
b++;
}
}
return b-1;
Thanks in advance!
Its because you are returning b-1. In fact, if you need to find the same instance and return the index, you wont even need the variable b. You could achieve this with something like this:
for( int a = 0; a < values.length; a++) {
if (values[a] == find){
return a;
}
}
return -1 // Notfound
}
Add the return -1 line for when a value is not found, to use as a sentinel value.
Try
for( int a = 0; a<values.length; a++) {
if (values[a] == find){
return a;
}
}
Why not return a itself instead of doing b-1;
Maybe you can add a break statement too to stop iterating as you just need the position of first instance
int b=0,result;
for( int a = 0; a<values.length; a++)
{
if (values[a] == find)
{
result=a;
break;
}
}
return result;

Categories

Resources