Assume that I have an array with the following values: 0,1,0,0,0,1,0,1,1
I am currently looping over my array and replacing 1's with 0's. However I would to break out of this loop if there are 2 1's left in my array. I don't really have much in terms of code but this is a stub of what I've been working on
if(//There are more than 2 1s ){
return true; //carry on looping
}
return false; //break the loop
I have no idea how to differentiate between the 0's and the 1's and so I am quite confused with how to get this to work. Any ideas would be appreciated.
One possible solution is to start by writing a utility method to test if a given value at a specific position is unique from every subsequent position in the array like,
private static boolean testUnique(int[] arr, int i) {
int t = arr[i];
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] == t) {
return false;
}
}
return true;
}
Then you can iterate the array from the left to the right, checking if every value is unique like
public static boolean hasDuplicate(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (!testUnique(arr, i)) {
return false;
}
}
return true;
}
Using your array,
public static void main(String[] args) {
int[] arr = { 0, 1, 0, 0, 0, 1, 0, 1, 1 };
System.out.println(hasDuplicate(arr));
}
That is false. Alternatively, you might find it easier if you first sort your array.
public int[] testDuplicatesofOne(int[] arr)
{
int count=0;
for(int i=0;i<arr.length-1;i++)
{
count+=(arr[i]>0?1:0);
}
if(count>=2)
{
for(int j=0;j<arr.length-1;j++)
{
if(count>2)
{
if(arr[j]==1)
{
arr[j]=0;
count--;
}
}else
{
break;
}
}
}
}
Hi Lukasz try this, Sorry if I have not understood your requirement properly.
Related
How can you get a subarray from a bigger array recursively, and without using copyOfRange?
For example if int[] a = {1,2,1,3,1,2,1,1,2}, and int[] b = {1,2}, the correct answer is 3.
This is the only recursive call I have, but I'm not sure what to do beyond this.
I know the base case should be if(a.length < b.length), but I don't understand how to count the occurrences.
The function returns return numSubstring(a,b,low, mid-1) + numSubstring(a,b, mid+1,high);
public static int countSubs(int [] data, int [] sub) {
int cnt = 0;
if (data.length < sub.length) {
return cnt;
}
boolean found = true;
for (int i = 0; i < sub.length; i++) {
if (data[i] != sub[i]) {
found = false;
break;
}
}
if (found) {
cnt++;
}
cnt += countSubs(Arrays.copyOfRange(data, 1, data.length), sub);
return cnt;
}
I know there are similar questions on stackoverflow, but none of their answers incorporated a return "-1" when no number is found.
Given an array list such as a = [4, 3, 9, 4, 6]
When entering a value such as v = 4, I want Java to give me the last index equivalent to that value in the array. So in this case, Java should return the index value 3.
If no values exist in the array such as v = 2, then I want it to return "-1".
This following solution I came up with finds the first index and returns it:
public static int lastIndexOf(int[] a, int v) {
int index = 0;
for(int i=0; i<a.length;i++) {
if(a[i]==v) {
index=i;
return index;
}
}
return -1;
}
This other solution I have, finds the last index in the array, but does not return "-1" when I enter a value that doesn't exist in the array.
public static int lastIndexOf(int[] a, int v) {
int index = 0;
for(int i=0; i<a.length;i++) {
if(a[i]==v) {
index=i;
}
}
return index;
}
I feel like I'm close to solving this, but I can't quite figure out how to mix these two solutions together.
In the second solution, just initialize the variable like this:
int index = -1;
Also consider traversing the array from right to left, in this way we can stop as soon as we find the element, it'll be more efficient:
public static int lastIndexOf(int[] a, int v) {
for (int i = a.length-1; i >= 0; i--)
if (a[i] == v)
return i;
return -1;
}
Assing int index = -1. Also a small optimization, loop from end, may be much faster for bigger loops:
public static int lastIndexOf(int[] a, int v) {
int index = -1;
for(int i=a.length-1; i >= 0; i--) {
if(a[i]==v) {
index=i;
return index;
}
}
return index;
}
sorry for the bad title I couldnĀ“t come up with anything better.
I want this to see if the array part[] have any elements that are 0. But i dont want it to check part[0].
if(Integer.parseInt(part[]) == 0)
So basiclly if i could do something like
if(Integer.parseInt(part[!=0]) == 0)
or
if(Integer.parseInt(part[<0]) == 0)
But obviously that wont work
To check if the array has any element with a value of 0, without checking the first index of the array, you could do:
boolean hasZero = false;
for (int i = 1; i < array.length(); i++) {
if (array[i] == 0) {
hasZero = true;
break;
}
}
Using the Stream api, it could be:
boolean hasZero = Arrays.stream(array).skip(1).anyMatch(i->i==0);
If you won't modify the array, you can create a copy of a range using Arrays.copyOfRange(int[] original, int from, int to):
import java.util.Arrays;
public static void main(String args[])
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
fun(Arrays.copyOfRange(arr, 2, arr.length), 3);
}
public static void fun(int a[], int n)
{
for (int i = 0; i < n; i++) {
System.out.printf("%d ", a[i]);
}
}
In Java 8 you can use a stream.
if (IntStream.range(1, part.length).anyMatch(i -> Integer.parseInt(part[i])==0)) {
// do stuff
}
I am trying to write a program using two methods that determines if a sub array is located within an array. subArray() is supposed to receive two arrays and return the index of the start of the sub array within the array. If the sub array is not located in the array it returns -1. subArray() then calls subArrayAppearsAt() and passes in the two arrays and a location. subArrayAppearsAt() is supposed to return true if the sub array is located in the array starting at the location passed in, false otherwise.
Currently if I pass in array {1,2,3} and sub array {2,3}, it returns 2 as the starting position but it should return 1.
If I pass in array {1,2,3,4,5} and sub array {4}, it returns -1, but it should return 3.
Does anyone see why this might be happening?
public static int subArray(int [ ] array, int [ ] subArray )
{
boolean result=true;
int subArrayLength = subArray.length;
if (subArrayLength == 0) {
return -1;
}
int limit = array.length - subArrayLength;
int i;
for ( i = 0; i <= limit; i++)
result = subArrayAppearsAt(array, subArray, i );
if (result==true)
return i;
else
return -1;
}
public static boolean subArrayAppearsAt(int[] largeArray, int[] subArray, int i) {
{
if (subArray[0] == largeArray[i])
{
boolean subArrayFound = true;
for (int j = 1; j < subArray.length; j++)
{
if (subArray[j] != largeArray[i+j])
{
subArrayFound = false;
j=subArray.length;
}
/* Sub array found - return its index */
if (subArrayFound==true)
{
return true;
}
}
}
}
/* Return default value */
return false;
}
Look at this part
for ( i = 0; i <= limit; i++)
result = subArrayAppearsAt(array, subArray, i );
it sets result every time it goes through the loop. If you test if {4} is conatined in {1, 2, 3, 4, 5} it will set result to the return value of subArrayAppearsAt(array, subArray, 4); which will return false
So for that problem you could do something like
for ( i = 0; i <= limit; i++) {
result = subArrayAppearsAt(array, subArray, i );
if (result==true)
return i;
}
return -1;
The other problem is, that i will be incremented after it goes into the for-loop the last time, and then you return that value. That problem should be solved with my code solution too.
I didn't test my solution but it should work ;)
EDIT
Sorry that wasn't all correct. Your subArrayAppearsAt() returns true too early. Edit your subArrayAppearsAt() function to this and it should work
public static boolean subArrayAppearsAt(int[] largeArray, int[] subArray, int i)
{
if (subArray[0] == largeArray[i])
{
for (int j = 1; j < subArray.length; j++)
{
if (subArray[j] != largeArray[i+j])
{
return false;
}
}
return true;
}
return false;
}
The problem is that if you want to know the start position you should put the if that checks the result inside de loop
public static int subArray(int [ ] array, int [ ] subArray )
{
boolean result=true;
int subArrayLength = subArray.length;
if (subArrayLength == 0) {
return -1;
}
int limit = array.length - subArrayLength;
int i;
for ( i = 0; i <= limit; i++){
result = subArrayAppearsAt(array, subArray, i );
if (result==true)
return i;
}
return -1;
}
public static void main(String[] args) {
int[] first = {1,2,4,5,3,2,1,3,4,5,6,33,432,21,5};
int[] second = {2,1};
System.out.println(findpos(first, second));
}
private static int findpos(int[] a, int[] b){
for(int i=0; i<a.length; i++){
if(a[i]!=b[0]){
continue;
}
if(a.length - i < b.length) return -1;
int itemp = i;
boolean found = true;
for(int j=0; j<b.length; j++){
if(itemp < a.length && a[itemp]!=b[j]){
found = false;
}
itemp++;
}
if(found){
return i;
}
}
return -1;
}
I'm trying to write a method that will accept an array and find any equal elements that appear next to each other and return a count for the greatest number of occurances. For example an array with the int values of {1,2,3,4,4,4,5,6} would return a value of 3. An array with {1,1,1,2,2,3,3,3,3,5,6,7} would return a value of four. I've tried a few different ways, but I'm struggling. Any help would be appreciated. Thanks. Heres the code that I have so far-
public class EqualElements
{
public static void consecutiveEqualElements(int [] elements)
{
int occurances = 0;
int temp = 0;
int count = 0;
for (int index = 0; index < elements.length; index++)
{
if(elements[index] == elements[temp])
{
count++;
temp++;
index--;
}
else
{
}
}
System.out.println(count);
}
public static void main(String[] args)
{
int [] numbers = {1,2,2,3,4,5,6,7};
consecutiveEqualElements(numbers);
}
}
Here is a much better way to look through an array for consecutive numbers. This will work for both unsorted and sorted arrays.
public static int consecutiveEqualElements(int [] elements) {
int currentNum = elements[0];
int currentConsecutive = 1;
int maxConsecutive = 1;
for (int i = 1; i < elements.length; i++) {
if (elements[i] == currentNum) {
currentConsecutive++;
maxConsecutive = Math.max(maxConsecutive, currentConsecutive);
} else {
currentNum = elements[i];
currentConsecutive = 1;
}
}
return maxConsecutive;
}
Easiest way is to use a hashmap:
Map map = new HashMap();
Now iterate through the array and put every integer with its count.
map.put(yourIntValue, map.get(1) + 1); // if it is already stored with a value.
For initial condition:
map.put(yourIntValue,0);
Then again iterate and find the max value.
My solution would look like this:
public class EqualElements {
public static void consecutiveEqualElements(int[] elements) {
// Saves the maximal number of consecutive number with the
// same numeric value
int occurances = 0;
// Counts how many numbers with the same value stands right
// behind each other
int count = 1;
// Run from the second index because of the in the body following
// if-clause
for (int index = 1; index < elements.length; index++) {
// In case the current and the previous element
// have the same numeric value
if (elements[index] == elements[index - 1]) {
// Increase the count (which is initialised with 1)
// And save the maximal number of consecutive numbers
// with the same value in occurances
count++;
occurances = Math.max(occurances, count);
} else {
// If the two numbers differ, reset the counter
count = 1;
}
}
System.out.println(occurances);
}
public static void main(String[] args) {
int[] numbers = { 1, 2, 2, 2, 3, 4, 5, 2, 6, 7 };
consecutiveEqualElements(numbers);
}
}
My example returns the correct solution 3. It doesn't count the last 2 since it's nonconsecutive.
You're already iterating over the array - that's good. While you do that you're interested in two numbers:
The longest run so far. This will be your answer in the end.
The length of the current run. You need this to update the longest run.
We create two variables for these: maxCount and count. During the loop, we increment count every time we encounter two consecutive elements that are equal. And to make sure maxCount is always up-to-date, we set it to the maximum of the longest so far, and the current length. When the next element is different from the previous, we reset count to 1, as this is the start of the next run.
public static void consecutiveEqualElements(int [] elements) {
int count = 1;
int maxCount = 1;
for (int index = 1; index < elements.length; index++) {
if (elements[index] == elements[index - 1]) {
count++;
maxCount = Math.max(maxCount, count);
} else {
count = 1;
}
}
System.out.println(maxCount);
}
Note: this method assumes that elements is not null or empty. You can handle these cases seperately, if they are necessary.
As you traverse the array, compare each element to the previous element. If the two elements are equal, increment the number of consecutive equal values you have seen. If they are not equal, check to see if you've found a new maximum, and then reset that counter to 0.
public static int consecutiveEqualElements(int[] elements) {
int max = 0;
int consecutive = 1;
for (int i = 1; i < elements.length; i++) {
if (elements[i] == elements[i-1]) {
consecutive++;
} else {
if (consecutive > max) {
max = consecutive;
}
consecutive = 1;
}
}
if (consecutive > max) {
return consecutive;
} else {
return max;
}
}
Notice that the method returns a value rather than printing it out. This makes the method more flexible, as you may not always want it to print to standard output.