Segregate_even_odd_numbers - java

given an array of integers, segregate even and odd numbers in the array. All the even numbers should be present first, and then the odd numbers.
Examples:
Input: arr[] = 1 9 5 3 2 6 7 11
Output: 2 6 5 3 1 9 7 11
Input: arr[] = 1 3 2 4 7 6 9 10
Output: 2 4 6 10 7 1 9 3
public class Segregate_even_odd_numbers {
public static void main(String[] args) {
int a[]= { 1, 3, 2, 4, 7, 6, 9, 10 };
int n=a.length;
int ind=0;
for(int i=0;i<n;i++){
if(a[i]%2==0){
a[ind]=a[i];
ind++;
}
}
for(int i=0;i<n;i++){
if(a[i]%2!=0){
a[ind]=a[i];
ind++;
}
}
for(int i=0;i<n;i++){
System.out.println(a[i] + " ");
}
System.out.println("");
}
}
I am getting output like this
2
4
6
10
7
9
9
10
0th index and 1st index not calculate.
what mistake I made, please guide me.

You're program is almost correct, but needs little modification, below is the implementation and explanation
public class Segregate_even_odd_numbers {
public static void main(String[] args) {
int a[] = { 1, 9, 5, 3, 2, 6, 7, 11 };
int n = a.length;
int evenIndex = 0;
for (int i = 0; i < n; i++) {
if (a[i] % 2 == 0) {
int temp = a[i];
a[i] = a[evenIndex];
a[evenIndex] = temp;
evenIndex++;
}
}
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
System.out.println("");
} }
What are we doing here:
We maintain a evenIndex pointer at 0 index
Whenever we find any Even value we swap it with evenIndex i.e.., arr[evenIndex] = arr[i] and place arr[i] = arr[evenIndex]
This code works does not modify any values if you pass an array with only Even Numbers or Odd Numbers
Time Complexity : O(n)
Space Complexity : O(1)

This can also be accomplished by sorting the array based on the value of each element modulo 2.
int[] a= { 1, 3, 2, 4, 7, 6, 9, 10 };
int[] res = Arrays.stream(a).boxed().sorted(Comparator.comparingInt(x -> x & 1))
.mapToInt(i -> i).toArray();
System.out.println(Arrays.toString(res));

Related

Find all combinations with repetitions but without duplicate rows

There is an array of 1, 2, 3, 4. It is necessary to make all possible combinations of 3 size series, the elements can be repeated. The order of the elements in the row is not important. For instance:
114 = 411 = 141.
I can't find a suitable algorithm. I have found this algorithm, but there can be no repetitions of elements, like 111 or 113, only 123,124 etc.
public void doit(){
String[] arr = {"1", "2", "3","4"};
int count = fuctorial(arr.length);
int max = arr.length - 1;
System.out.println("Вариантов " + count);
int shift = max;
String t;
while (count > 0) {
t = arr[shift];
arr[shift] = arr[shift - 1];
arr[shift - 1] = t;
print(arr);
count--;
if (shift < 2) {
shift = max;
} else {
shift--;
}
}
}
static void print(String[] arr) {
System.out.println(Arrays.toString(arr));
}
static int fuctorial(int n) {
return (n > 0) ? n * fuctorial(n - 1) : 1;
}
Try this.
static void combination(int[] a, int n) {
int size = a.length;
int[] selected = new int[n];
new Object() {
void print() {
for (int i = 0; i < n; ++i)
System.out.print(a[selected[i]] + " ");
System.out.println();
}
void combination(int index, int prev) {
if (index >= n)
print();
else
for (int i = prev; i < size; ++i)
combination(index + 1, selected[index] = i);
}
}.combination(0, 0);
}
and
int[] a = {6, 7, 8, 9};
combination(a, 3);
output:
6 6 6
6 6 7
6 6 8
6 6 9
6 7 7
6 7 8
6 7 9
6 8 8
6 8 9
6 9 9
7 7 7
7 7 8
7 7 9
7 8 8
7 8 9
7 9 9
8 8 8
8 8 9
8 9 9
9 9 9
public void func() {
boolean[] check = new boolean[49];
for(int i=1; i <=4; i++ ) {
for(int j=1; j <=4; j++) {
for(int k=1; k<=4; k++) {
int sum = i*i + j*j + k*k;
if(!check[sum]) {
check[sum] = true;
System.out.println(i + "," + j + "," + k);
}
}
}
}
}
idea is: we take a triplet, calculate the sum of squares, and check if we already had a triplet with that sum. identical triplets will have the same sum of squares.
the sum of squares will always be in the range 3-48. also, the sum is unique to each combination of numbers just like you require.
Complexity is O(N^3) where N is the size of the array. since we need combinations of 3 elements, i don't think you can go below that.
UPDATE: to make is more general, use a HashSet for the sums instead of the boolean array, and iterate 3 nested loops over the input array. calculate the sum of squares and check against the HashSet.
Performance Optimization: calculate the squares of each element in the array in advance so you dont have to calculate them over and over again.

How can I optimize this solution? (Cutting a specific part of an array given bounds)

I'm given a list of numbers, and given a number N, cut out N numbers from the center of the list. So, if the list is:
1 2 3 5 7 11 13 17 19
And N = 3, output would be:
5 7 11
Or if the list is:
1 2 3 5 7 11 13 17
And N = 4, output would then be:
3 5 7 11
My current solution is O(N^2) (or at least I think it is? Idk if that nested for loop would mean this is O(N^2)), where I iterate over the array of numbers until the amount of numbers from the start to i is == the amount of numbers from (size of array - (i + cut size)). Because a cut in the middle would mean there's the same amount of numbers on the left side of the cut as the right side.
"nums" is the array of numbers I'm finding a cut in the middle for.
int rightof = 0;
ArrayList<Integer> cut = new ArrayList<Integer>();
for (int i = 0; i < nums.size(); i++) {
rightof = nums.size() - (i + cutsize);
if (i == rightof && i != 0) {
for (int j = i; j < (cutsize + i); j++) {
cut.add(nums.get(j));
}
break;
}
}
The thing that's slowing this down is adding the appropriate numbers to the "cut" array. So I'm not sure how I might optimize that step.
The Java 8 stream api makes this fairly easy. The number of elements to skip is the size minus n divided by two, and limit to n elements.
List<Integer> cut = Arrays.asList(1, 2, 3, 5, 7, 11, 13, 17, 19);
int n = 3;
int sk = (cut.size() - n) / 2;
List<Integer> al = cut.stream().skip(sk).limit(n).collect(Collectors.toList());
System.out.println(al);
Learn the power of sublist():
List<T> result = arr.subList((arr.size()+1)/2 - arr.size()/4, arr.size()/2 + arr.size()/4);
Where arr is your List
Example:
List<Integer> arr = Arrays.asList(1, 2, 3, 5, 7, 11, 13, 17);
arr.subList((arr.size()+1)/2 - arr.size()/4, arr.size()/2 + arr.size()/4)
.forEach(System.out::println);
Output:
3
5
7
11
If you just want to do this with simple loops:
List<Integer> list = new ArrayList<>();
int size = arr.size();
for(int i = (size+1)/2-size/4; i < size/2+size/4; i++) {
list.add(arr.get(i));
}

Shuffling array.Output not correct

I have been working on this program and randomly shuffles the contents of an array of integers.
This is what is supposed to look like:
Array contents: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Do you wish to shuffle these numbers? y
Array contents: 5 12 7 10 6 9 15 1 13 3 4 11 14 2 8
Do you wish to shuffle these numbers? y
Array contents: 2 9 15 4 12 11 3 7 10 8 1 6 13 5 14
Do you wish to shuffle these numbers? n
This is what im getting:
Array Contents: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
Do you wish to shuffle these numbers? y
Exception in thread "main" java.lang.NumberFormatException: For input string: "y"
and says build failed
This is the main code:
public class Evao1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner kp = new Scanner(System.in);
final int size = 15;
char q = 'y';
boolean flag = false;
Shuffler myShuffler = new Shuffler(size);
Scanner input = new Scanner(System.in);
for(;;) {
myShuffler.display();
System.out.println();
System.out.print("Do you wish to shuffle these numbers? ");
String value = input.next();
if (value.equals("q")) break;
int value1 = Integer.parseInt(value);
}
}
}
Here is the additional class:
public class Shuffler {
private int[] data;
public Shuffler(int size){
data = new int[size];
for (int i = 0; i < size; i++)
{
data[i] = i + 1;
}
}
public void shuffle(){
for (int i = 0; i < data.length; i++)
{
Random r = new Random(15);
int second = r.nextInt(15) + 1;
int temp = data[i];
data[i] = data[second];
data[second] = temp;
}
}
public void display()
{
String values = "";
for (int i = 0; i < data.length; i++)
{
if (i < 15)
{
values += (i + 1);
if (i < 14)
{
values += ", ";
}
}
}
System.out.printf("Array Contents: %s \n", values);
}
}
The problem is with the last two lines of your for loop in the Evao1 class.
First, I think you meant to write if (value.equals("n")) break;
Second, instead of int value1 = Integer.parseInt(value);
Just do myShuffler.shuffle();
Also, in the for loop of display() you aren't actually displaying anything from the data array.
Change values += (i + 1); to values += data[i];

Shifting an array. Output is not correct.

I have been working on this program and will display the array contents to the user and ask how many positions he would like to shift off the right side of the array, and replace onto the left side.
This is what is supposed to look like:
Array contents: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Shift how many positions? 5
Array contents: 11 12 13 14 15 1 2 3 4 5 6 7 8 9 10
Shift how many positions? 2
Array contents: 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8
Shift how many positions? 0
Array contents: 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8
Shift how many positions? -8
Array contents: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1
Shift how many positions? 15
Array contents: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1
Shift how many positions? 17
Array contents: 15 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Shift how many positions? q
And im getting this:
Array Contents: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
Shift how many positions?5
Array Contents: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
Here is the main class:
public class Shift1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner kp = new Scanner(System.in);
final int size = 15;
char q = 'y';
boolean flag = false;
Shifter test = new Shifter(size);
test.display();
System.out.println();
Scanner input = new Scanner(System.in);
System.out.print("Shift how many positions?");{
int value1 = input.nextInt();
test.shift(value1);
test.display();
}
}
}
And here is additional class:
public class Shifter
{
public int [] data=new int[15];
public Shifter()
{
int size=0;
}
public Shifter(int size){
for (int i = 0; i < data.length; i++)
{
Random r = new Random(15);
int second = r.nextInt(15) + 1;
int temp = data[i];
data[i] = data[second];
data[second] = temp;
}
}
public void shift(int pos){
for(int x=0; x<pos; x++)
{
int cnt = data.length-1;
int temp = data[cnt];
for(cnt=data.length-1; cnt>0; cnt--)
{
data[cnt] = data[cnt]-1;
}
data[0] =temp;
}
}
public void display(){
String values = "";
for (int i = 0; i < data.length; i++)
{
if (i < 15)
{
values += (i + 1);
if (i < 14)
{
values += ", ";
}
}
}
System.out.printf("Array Contents: %s \n", values);
} }
Introduce a loop in main() method.
Firstly read as string in order to recognize q.
Implement Shifter.shift() properly.
Add a space after the prompt.
Initialize the array properly.
Implement Shifter.display() properly.
Corrected codes:
public static void main(String[] args) {
Scanner kp = new Scanner(System.in);
final int size = 15;
char q = 'y';
boolean flag = false;
Shifter test = new Shifter(size);
Scanner input = new Scanner(System.in);
for(;;) {
test.display();
System.out.println();
System.out.print("Shift how many positions? ");
String value = input.next();
if (value.equals("q")) break;
int value1 = Integer.parseInt(value);
test.shift(value1);
}
}
public Shifter(int size){
for (int i = 0; i < data.length; i++)
{
data[i] = i + 1;
}
}
public void shift(int pos){
int max = pos % data.length;
if (max < 0) max += data.length;
for (int x=0; x<max; x++)
{
int cnt = data.length-1;
int temp = data[cnt];
for(cnt=data.length-1; cnt>0; cnt--)
{
data[cnt] = data[cnt-1];
}
data[0] =temp;
}
}
public void display(){
String values = "";
for (int i = 0; i < data.length; i++)
{
values += " ";
if (data[i] < 10) values += " ";
values += data[i];
}
System.out.printf("Array Contents: %s \n", values);
}
Though there are more points to be improved, this works as you said.
for(int x=0; x<pos; x++) {
int cnt = data.length-1;
int temp = data[cnt];
for(cnt=data.length-1; cnt>0; cnt--) {
data[cnt] = data[cnt]-1;
}
data[0] =temp;
}
In your shift method you should be utilizing your x for loop variable. cnt and temp are always the same no matter what. So your not really doing anything in this loop.
If your allowed to use something other than an Array, maybe take a look at using a List. It has a unique method such as
http://docs.oracle.com/javase/7/docs/api/java/util/List.html#add(int,%20E)
which will allow you to add a number at the 0 index and it will auto shift the existing values right. So pop a value off the end and move it to the front size amount of times.

Executing each Array of Integers in a certain position of an ArrayList

I have an ArrayList:
ArrayList<Integer> list = new ArrayList<>();
And an Array of Integers:
int[] x = {5, 10, 15, 20, 25};
I want to execute each Array of Integers in a certain position of the ArrayList. I’ve tried the following code but it's not working as expected!
public static void main(String[] args) {
// TODO code application logic here
for(int i = 1; i <= 30; i++) {
list.add(i);
}
for(int i = 0; i < list.size(); i++) {
System.out.print(i);
System.out.print(" , ");
System.out.print(number(i));
}
}
private static long number(int pos) {
int y = 0;
return (long) pos / list.get(x[y]);
}
Current Output:
0 , 0
1 , 0
2 , 0
3 , 0
4 , 0
5 , 0
6 , 1
7 , 1
8 , 1
9 , 1
10 , 1
11 , 1
12 , 2
.
.
.
Expected Output (something like):
0 , 0
1 , 0
2 , 0
3 , 0
4 , 0
5 , 5
6 , 5
7 , 5
8 , 5
9 , 5
10 , 10
11 , 10
12 , 10
.
.
.
I tried different methods but couldn't manage to solve it, any help is very much appreciated.
I will answer like you want to follow the pattern in your expected answer, first of all, when you say list.get(x[y]) it gives you list.get(5) which is 6 as you started to count from 1 not 0 when filling the list, So you are preferred to do one of two options:
1- make your count from 0:
for(int i = 0; i < list.size(); i++) {
.
.
}
2- make your get line with x[y]-1:
list.get(x[y] - 1);
And in both cases when you want to get the result, you must multiply it with the value of the list index which is x[y]:
private static long number(int pos) {
int y = 0;
return Math.round(pos / list.get(x[y]) * x[y]);
}
I think it's because y variable inside number method is always 0. Because of that number method always returns pos / list.get(5). That's why 2nd number increases when number is divisible by 6. From what I noticed your expected output is number divided by 1 rounded down to nearest 5.
What I suggest you to do is to maintain a counter variable to check if the number in the array has reached or not.
int []arr = {2, 5, 10, 15, 20, 30};
int size = arr[arr.length - 1];
ArrayList<Integer> list = new ArrayList();
int k = 0;
for(int i = 0; i < size; ++i)
{
if(i == arr[k])
k ++;
if(k == 0)
list.add(0);
else
list.add(arr[k - 1]);
}
for(int i = 0; i < size; ++i)
System.out.println(i + ", " + list.get(i));
Output:
0, 0
1, 0
2, 2
3, 2
4, 2
5, 5
6, 5
...
private static long number(int pos) {
return list.get(pos);
}

Categories

Resources