Related
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.
So basically, I've been going through these codingBat problems, and when I get really stuck, I usually check out the solution and trace the logic and that has helped me not get stuck on later problems which used similar ideas.
This max mirror problem is not like the others for me personally; I have no idea how to actually write the code to solve it, even forming the algorithm is kind of tricky for me
We'll say that a "mirror" section in an array is a group of contiguous elements such that somewhere in the array, the same group appears in reverse order. For example, the largest mirror section in {1, 2, 3, 8, 9, 3, 2, 1} is length 3 (the {1, 2, 3} part). Return the size of the largest mirror section found in the given array.
maxMirror({1, 2, 3, 8, 9, 3, 2, 1}) → 3
maxMirror({1, 2, 1, 4}) → 3
maxMirror({7, 1, 2, 9, 7, 2, 1}) → 2
Now, in terms of the algorithm, I sort of want to say something like, if we start by checking if the whole array is a mirror and then decrease the checked area size by 1 if it's not. But in terms of the pseudocode and the real code I have no idea.
My go to solution in cases like this where what your code should be doing is always doing it manually, then figuring out the essence of how it is that I am tackling the solution.
For this problem I found myself looking at possible subsets of the original array, then looking backwards through the original array to see if I can find that same subset again.
Next, I translated that into pseudocode,
for each segment in nums
check if nums contains segment backwards
Repeated, but this time with more implementation details worked out.
for each segment in nums, starting with the largest
reverse the segment
check if nums contains reversed segment
if it does, return the size of that segment
Next, find some likely candidates for methods in the pseudocode and write them. I chose to do this for "reverse" and "contains":
private int[] reverse(int[] nums) {
int[] rtn = new int[nums.length];
for (int pos = 0; pos < nums.length; pos++) {
rtn[nums.length - pos - 1] = nums[pos];
}
return rtn;
}
private boolean contains(int[] nums, int[] segment) {
for (int i = 0; i <= nums.length - segment.length; i++) {
boolean matches = true;
for (int j = 0; j < segment.length; j++) {
if (nums[i + j] != segment[j]) {
matches = false;
break;
}
}
if (matches) return true;
}
return false;
}
Finally, implement the rest:
public int maxMirror(int[] nums) {
for (int window = nums.length; window > 0; window--) {
for (int pos = 0; pos <= nums.length - window; pos++) {
int[] segment = new int[window];
for (int innerpos = 0; innerpos < window; innerpos++) {
segment[innerpos] = nums[pos + innerpos];
}
segment = reverse(segment);
if (contains(nums, segment)) {
return window;
}
}
}
return 0;
}
My irrelevant two cents....
public int maxMirror(int[] nums) {
// maximum mirror length found so far
int maxlen= 0;
// iterate through all possible mirror start indexes
for (int front = 0; front < nums.length; front++) {
// iterate through all possible mirror end indexes
for (int back = nums.length - 1; back >= front; back--) {
// this inner for-loop determines the mirror length given a fixed
// start and end index
int matchlen = 0;
Boolean match = (nums[front] == nums[back]);
// while there is a match
// 1. increment matchlen
// 2. keep on checking the proceeding indexes
while (match) {
matchlen++;
int front_index = front + matchlen;
int back_index = back - matchlen;
// A match requires
// 1. Thee indexes are in bounds
// 2. The values in num at the specified indexes are equal
match =
(front_index < nums.length) &&
(back_index >= 0) &&
(nums[front_index] == nums[back_index]);
}
// Replace the max mirror length with the new max if needed
if (matchlen > maxlen) maxlen = matchlen;
}
}
return maxlen;
}
Alternative solution designed to confuse you
public int maxMirror(int[] nums) {
return maxlen_all_f(nums, 0);
}
int maxlen_all_f(int [] nums, int f) {
return (f >= nums.length)
? 0
: max(
maxlen_for_start_f(nums, f, nums.length - 1),
maxlen_all_f(nums, f + 1)
);
}
int max(int a, int b){
return (a > b)
? a
: b;
}
int maxlen_for_start_f(int [] nums, int f, int b) {
return (b < f)
? 0
: max(
matchlen_f(nums, f, b),
maxlen_for_start_f(nums, f, b - 1)
);
}
int matchlen_f(int[] nums, int f, int b) {
return match_f(nums, f, b)
? 1 + matchlen_f(nums, f + 1, b - 1)
: 0;
}
Boolean match_f(int [] nums, int a, int b) {
return (a < nums.length && b >= 0) && (nums[a] == nums[b]);
}
The solution is simple rather than making it complex:
public static int maxMirror(int[] nums) {
final int len=nums.length;
int max=0;
if(len==0)
return max;
for(int i=0;i<len;i++)
{
int counter=0;
for(int j=(len-1);j>i;j--)
{
if(nums[i+counter]!=nums[j])
{
break;
}
counter++;
}
max=Math.max(max, counter);
}
if(max==1)
max=0;
return max;
}
This is definitely not the best solution in terms of performance. Any further improvements are invited.
public int maxMirror(int[] nums) {
int maxMirror=0;
for(int i=0;i<nums.length;i++)
{
int mirror=0;
int index=lastIndexOf(nums,nums[i]);
if(index!=-1){
mirror++;
for(int j=i+1;j<nums.length;j++)
{
if(index>=0&&existsInReverse(nums,index,nums[j]))
{
mirror++;
index--;
continue;
}
else
break;
}
if(mirror>maxMirror)
maxMirror=mirror;
}
}
return maxMirror;
}
int lastIndexOf(int[] nums,int num){
for(int i=nums.length-1;i>=0;i--)
{
if(nums[i]==num)
return i;
}
return -1;
}
boolean existsInReverse(int nums[],int startIndex,int num){
if(startIndex!=0&&(nums[startIndex-1]==num))
return true;
return false;
}
Here is my answer , Hope the comments explain it well :)
public int maxMirror(int[] nums) {
int max = 0;
// our largest mirror section found stored in max
//iterating array
for(int i=0;i<nums.length;i++){
int iterator = i; // iterator pointing at one element of array
int counter = 0;//counter to count the mirror elements
//Looping through for the iterator element
for(int j=nums.length-1;j>=i;j--){
//found match i.e mirror element
if(nums[iterator] == nums[j]){
iterator++; // match them until the match ends
counter++; // counting the matched ones
}
else{
//matching ended
if(counter >= max){//checking if previous count was lower than we got now
max = counter; // store the count of matched elements
}
counter = 0; // reset the counter
iterator = i; // reset the iterator for matching again
}
}
if(counter >= max){//checking if previous count was lower than we got now
max = counter;// store the count of matched elements at end of iteration
}
}
return max;//return count
}
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.
import java.util.*;
public class FirstOddOccurrence {
public static void main(String[] args) {
int[] x = {2, 4, 6, 7, 4, 3, 2, 7, 6, 7, 7};
int i;
display(x);
System.out.printf("# Occurrences of first odd = %3d\n", firstOddCount(x));
}
private static void display(int[] x) {
int i;
System.out.print("Array: ");
for (i = 0; i < x.length; i++) {
if (i < x.length - 1)
System.out.printf("%3d, ", x[i]);
else
System.out.printf("%3d\n", x[i]);
}
}
public static int odd(int[] x) {
int i;
int y;
for (i = 0; i < x.length; i++) {
y = x[i] % 2;
if (y == 1) {
return x[i];
} else {
return 0;
}
}
return x[i];
}
public static int firstOddCount(int x[]) {
int i;
int c = 0;
for (i = 0; i < x.length; i++) {
if (x[i] == odd(x))
c++;
}
return c;
}
}
I'm trying to find the first occurrence of an odd number in the array that has been provided. What is wrong with my program? I can't seem to get the program to count the first odd occurrences.
Your code here:
if (y == 1) {
return x[i];
} else {
return 0;
}
does not work - if a tested number is even, you immediately return 0. Instead you want to skip these even numbers and wait until an odd number comes up. In the end, if you don't find any odd number, you return 0. Here is the corrected version of odd():
int i;
int y;
for (i = 0; i < x.length; i++) {
y = x[i] % 2;
if (y == 1) {
return x[i];
}
}
return 0;
Andr's solution fixes your issue; odd(x) will return 0 if x[0] is even, and x[0] if it is odd.
You could also improve firstOddCount like so: odd(x) will always return the same value, so only calculate it once.
public static int firstOddCount(int x[]) {
int firstOdd = odd(x);
int c=0;
for(int i=0; i < x.length; i++) {
if (x[i]==firstOdd)
c++;
}
return c;
}
Your particular problem is that you return 0 if you find an even number. That means that the list {2, 4, 6, 8, 1} will give you 0, rather than 1, as the first odd number.
What you should do is ignore leading even numbers and continue to process the list.
However, the way you've organised your program, you're processing the first all-even part of the list twice, once in odd() to find the first odd number, then again in firstOddCount() to count how many of that number there are - that's totally unnecessary.
Once you find the first odd number, I think you can be reasonably certain that number (or any other odd number for that matter) does not exist in the space you've already searched. Otherwise it would have been the first odd number. Hence it makes little sense to go back and look at that initial part of the list again.
A way in which you can easily just process the list once is as follows:
public static int firstOddCount (int numbers[]) {
// Find first odd number or end of list.
int idx = 0, len = numbers.length;
while ((idx < len) && ((numbers[idx] % 2) == 0)
idx++;
// If at end of list, everything is even => count(first(odd)) is 0.
if (idx == len)
return 0;
// Otherwise, start counting from current position.
int count = 1, oddnum = numbers[idx];
while (++idx < len)
if (numbers[idx] == oddnum)
count++;
return count;
}
If you are trying to get one element from group you should use 'break' when your condition matched first time else it will give all...
I have an array where I have some numbers. Now I want to sort even numbers in a separate array and odd numbers in a separate. Is there any API to do that? I tried like this
int[] array_sort={5,12,3,21,8,7,19,102,201};
int [] even_sort;
int i;
for(i=0;i<8;i++)
{
if(array_sort[i]%2==0)
{
even_sort=Arrays.sort(array_sort[i]);//error in sort
System.out.println(even_sort);
}
}
Plain and simple.
int[] array_sort = {5, 12, 3, 21, 8, 7, 19, 102, 201 };
List<Integer> odd = new ArrayList<Integer>();
List<Integer> even = new ArrayList<Integer>();
for (int i : array_sort) {
if ((i & 1) == 1) {
odd.add(i);
} else {
even.add(i);
}
}
Collections.sort(odd);
Collections.sort(even);
System.out.println("Odd:" + odd);
System.out.println("Even:" + even);
Your question as stated doesn't make sense, and neither does the code. So I'm guessing that you want to separate the elements of an array into two arrays, one containing odds and the other evens. If so, do it like this:
int[] input = {5, 12, 3, 21, 8, 7, 19, 102, 201};
List<Integer> evens = new ArrayList<Integer>();
List<Integer> odds = new ArrayList<Integer>();
for (int i : input) {
if (i % 2 == 0) {
evens.add(i);
} else {
odds.add(i);
}
}
You can then convert a list of Integer to a sorted array if int as follows:
List<Integer> list ...
int[] array = new int[list.size()];
for (int i = 0; i < array.length; i++) {
array[i] = list.get(i);
}
Arrays.sort(array);
or if a sorted List<Integer> is what you need, just do this:
Collections.sort(list);
It's simple to do this using Guava.
Use Ints.asList to create a List<Integer> live view of an int[]
Define a Function<Integer,Boolean> isOdd
Use Ordering that compares onResultOf(isOdd), naturally (i.e. false first, then true)
If necessary, compound that with an Ordering.natural()
Here's the snippet:
int[] nums = {5,12,3,21,8,7,19,102,201};
Function<Integer,Boolean> isOdd = new Function<Integer,Boolean>() {
#Override
public Boolean apply(Integer i) {
return (i & 1) == 1;
}
};
Collections.sort(
Ints.asList(nums),
Ordering.natural().onResultOf(isOdd)
.compound(Ordering.natural())
);
System.out.println(Arrays.toString(nums));
// [8, 12, 102, 3, 5, 7, 19, 21, 201]
Note that all the even numbers show up first, then all the odd numbers. Within each group, the numbers are sorted naturally.
External links
polygenelubricants.com - Writing more elegant comparison logic with Guava's Ordering
There are some things to know first :
You must initialize an array before using it. For example int[] even_sort = new int[3];
In java arrays have a static size. That means that you won't be able to add as many elements as you want. You have to choose a size before. You should take a look at Java Collections, it's a good way to get rid of this "rule" the java way.
The Arrays.sort() method apply on arrays only. Here array_sort[i] is an int
Arrays.sort() sorts an array but doesn't return anything.
If you really want to use arrays (but you shouldn't) you can do something like this to resize one :
int[] even_sort = new int[3]{1, 2, 3};
int[] temp = new int[4];
System.arraycopy(even_sort, 0, temp, 0, even_sort.length);
even_sort = temp;
even_sort[3] = 4;
Another way would be creating an utility method which uses reflection to create the new array :
import java.lang.reflect.Array;
public Object resizeArray(Object originalArray, int newSize){
int originalSize = Array.getLength(originalArray);
Class arrayType = originalArray.getClass().getComponentType();
Object newArray = Array.newInstance(arrayType, newSize);
System.arraycopy(originalArray, 0, newArray, 0, Math.min(originalSize, newSize));
return newArray;
}
So if you still want to use array for some reasons (but you still shouldn't) here is a code to filter, resize and sort your array.
int[] arrayToFilterAndSort = {5, 12, 3, 21, 8, 7, 19, 102, 201};
int[] sortedEvens = new int[0];
for(int current : arrayToFilterAndSort){
if((current & 1) == 1){
sortedEvens = resizeArray(sortedEvens, sortedEvens.length + 1);
sortedEvens[sortedEvens.length - 1] = current;
}
}
Arrays.sort(sortedEvens);
Resources :
oracle.com - Arrays tutorial
oracle.com - Collections tutorial
javadoc - Arrays.sort()
package com.java.util.collection;
import java.util.Arrays;
/**
* Given n random numbers. Move all even numbers on left hand side and odd numbers on right hand side and
* then sort the even numbers in increasing order and odd numbers in decreasing order For example,
* i/p : 3 6 9 2 4 10 34 21 5
* o/p: 2 4 6 10 34 3 5 9 21
* #author vsinha
*
*/
public class EvenOddSorting {
public static void eventOddSort(int[] arr) {
int i =0;
int j =arr.length-1;
while(i<j) {
if(isEven(arr[i]) && isOdd(arr[j])) {
i++;
j--;
} else if(!isEven(arr[i]) && !isOdd(arr[j])) {
swap(i,j,arr);
} else if(isEven(arr[i])){
i++;
} else{
j--;
}
}
display(arr);
// even number sorting
Arrays.sort(arr,0,i);
Arrays.sort(arr,i,arr.length);
// odd number sorting
display(arr);
}
public static void display(int[] arr) {
System.out.println("\n");
for(int val:arr){
System.out.print(val +" ");
}
}
private static void swap(int pos1, int pos2, int[] arr) {
int temp = arr[pos1];
arr[pos1]= arr[pos2];
arr[pos2]= temp;
}
public static boolean isOdd(int i) {
return (i & 1) != 0;
}
public static boolean isEven(int i) {
return (i & 1) == 0;
}
public static void main(String[] args) {
int arr[]={3, 6, 9 ,2, 4, 10, 34, 21, 5};
eventOddSort(arr);
}
}
int arr[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cout << "The Even no are : \n";
for (int i = 1; i <= 10; i++) // for start for only i....(even nos)
{
if (i % 2 == 0)
{
cout << i;
cout << " ";
}
}
cout << "\nThe Odd no are : \n";
for (int j = 1; j <= 10; j++) // for start for only j....(odd nos)
{
if (j % 2 != 0)
{
cout << j;
cout << " ";
}`enter code here`
}
package srikanth dukuntla;
public class ArrangingArray {
public static void main(String[] args) {
int j=0;
int []array={1,2,3,5,4,55,32,0};
System.out.println(array.length);
int n=array.length/2;
for (int i=0; i<array.length; i++){
if(array[i]%2!=0){
j=1;
int temp=array[array.length-j];
if(temp % 2!=0){
while((array[array.length-(j+1)]%2!=0) && (array.length-(j+1)>n)){
j++;
}
int temp2=array[array.length-(j+1)];
array[array.length-(j+1)] =array[i];
array[i]=temp2;
}else // inner if
{
array[array.length-j] =array[i];
array[i]=temp;
}
}else //main if
{
//nothing needed
}
}
for(int k=0;k<array.length;k++) {
System.out.print(" "+ array[k]);
}
}
}
List < Integer > odd = new ArrayList < Integer > ();
List < Integer > even = new ArrayList < Integer > ();
int a [] = {0,2,3,98,1,6546,45323,1134564};
int i;
for (i = 0; i < a.length; i++) {
if (a[i] % 2 == 0) {
even.add(a[i]);
} else {
odd.add(a[i]);
}
}
System.out.print("Even: " + even + "\n");
System.out.print("Uneven: " + odd + "\n");
}
}