Related
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));
Given two numbers, s (sum)
and n (posit number, ii), there are several ways in which I can express and,
as a sum of n whole numbers, strictly positive.
for s = 7, n = 3; 7 = 4 + 2 + 1 and
7 = 1 + 4 + 2 are not considered distinct.
I have to calculate i th solution.
Example for input:
11
6
5
example for output:
11=3+2+2+2+1+1 (5th mode to compose the sum)
I tried to use backtraking to compose these sums but the algorithm does not produce all the solutions.
static boolean checkSum(int sum, int remPos, int elem) {
if (sum < remPos)
return false;
if (sum > remPos * elem)
return false;
return true;
}
private ArrayList<Integer> back(ArrayList<Integer> sol, int crtPos,
int sum, ArrayList<Integer> ans) {
//the solution was found
if (index == i) {
ans.addAll(sol);
return sol;
} else if (index > i) {
return null;
}
if (crtPos == k + 1) {
crtPos = 1;
index++;
}
for (int j = sol.get(crtPos - 1); j > 0; j--) {
//add to solution
sol.add(crtPos, j);
//decreases from the remaining sum
sum -= j;
//check
if (checkSum(sum, k - crtPos, j)) {
sol = back(sol, crtPos + 1, sum, ans);
}
//remove from solution
sol.remove(crtPos);
sum += j;
}
return sol;
}
Don't know what is wrong with your code, but let me give you an alternate algorithm that doesn't use recursion, and doesn't require boxing the values.
First, you said that order of values doesn't matter, e.g. 7 = 4 + 2 + 1 and 7 = 1 + 4 + 2 is the same solution. In the algorithm below, we ensure that by stating that values must be in ascending order, e.g. 7 = 1 + 2 + 4.
Let me illustrate algorithm using example of s=10, n=5, which for reference gives the following solutions:
10 = 1 + 1 + 1 + 1 + 6
10 = 1 + 1 + 1 + 2 + 5
10 = 1 + 1 + 1 + 3 + 4
10 = 1 + 1 + 2 + 2 + 4
10 = 1 + 1 + 2 + 3 + 3
10 = 1 + 2 + 2 + 2 + 3
10 = 2 + 2 + 2 + 2 + 2
First, build an int[] and fill it with 1's, except the last value is s - (n-1), aka s - n + 1 (where n-1 is the sum of the 1's):
[1, 1, 1, 1, 6]
That is your first solution.
Now we "increment" that to the next solution, where the last value is always calculated, i.e. the next solution is:
[1, 1, 1, 2, x] where x = s - (1+1+1+2) = 5
[1, 1, 1, 2, 5]
We continue that as long as last value >= second last value:
[1, 1, 1, 3, 4]
Next one would have been [1, 1, 1, 4, 3] but that violates our constraint, so be walk backwards to previous value, and increment that. Since values must be ascending, we will fill the following positions with the same value (represented as = below), except we calculate the last value (x):
[1, 1, 2, =, x] where x = s - (1+1+2+2) = 4
[1, 1, 2, 2, 4]
Next one is easy:
[1, 1, 2, 3, 3]
Now we can't increment the 3rd position from 2 to 3, because that would give us [1, 1, 3, 3, 2] so we walk back one more position:
[1, 2, =, =, x] where x = s - (1+2+2+2) = 3
[1, 2, 2, 2, 3]
Now we have to walk back one more time:
[2, =, =, =, x] where x = s - (2+2+2+2) = 2
[2, 2, 2, 2, 2]
And we're done, because we can't walk any further back.
Here is code in compact form:
public static void compose(int s, int n) {
if (s < n || n < 1)
throw new IllegalArgumentException();
int[] values = new int[n];
Arrays.fill(values, 1);
values[n - 1] = s - n + 1;
for (;;) {
printSolution(s, values);
int i = n - 1, remain = values[i];
for (; --i >= 0; remain += values[i])
if (--remain >= ++values[i] * (n - i - 1))
break;
if (i < 0)
break;
Arrays.fill(values, i + 1, n, values[i]);
values[n - 1] = remain - values[i] * (n - i - 2);
}
}
public static void printSolution(int s, int[] values) {
System.out.print(s + " = " + values[0]);
for (int i = 1; i < values.length; i++)
System.out.print(" + " + values[i]);
System.out.println();
}
Output from compose(7, 3)
7 = 1 + 1 + 5
7 = 1 + 2 + 4
7 = 1 + 3 + 3
7 = 2 + 2 + 3
Output from compose(10, 5) is already shown earlier.
If you just need the i'th solution, remove the printSolution call, change the forever loop to loop i-1 times, and return the values array.
I have 2 Arrays:
A {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
B {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
I want to make the user be able to input a x number and then the program should print out all possible multiplications that = x.
the multiplication that = x should be made of 2 numbers 1 of array A and the other number from array B. The numbers cannot be the same.
I've been searching and the only thing I think could work is a nested loop.
I am doing this little project in C# but I kindly don't care if it's in Java I understand also Java.
Thanks in advance for the help.
int num_user;
int[] x = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, };
int[] y = new int[9];
Console.WriteLine("Hello please input the number you think could be the solution :) ");
num_user = Convert.ToInt32(Console.ReadLine());
for (int a = 0; a < x.Length; a++ )
for (int b = 0; b < y.Length; b++)
if num_user == a*b //and here is where I get lost
int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] b = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int target = 5; //The number you want the 2 numbers to multiply to
var query =
from x in a
from y in b
where y != x && x * y == target
select new { x, y };
foreach (var pair in query) Console.WriteLine(pair);
a simple nested loop would work for this
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < 10; y++)
{
if (x != y && x*y == your_number) System.out.format("%d * %d = %d\n",x,y,your_number);
}
}
code not tested, but sth like this should work.
you'll have to implement the arrays for yourself :)
using System;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
string input = string.Empty;
int output = 0;
do
{
Console.WriteLine("Enter number: ");
input = /* Console.ReadLine(); */ "8";
} while (!int.TryParse(input, out output));
int[] first = new int[] {0,1,2,3,4,5,6,7,8,9};
int[] second = new int[] {0,1,2,3,4,5,6,7,8,9};
var list = new List<string>();
for (int i = 0; i < first.Length; i++)
for (int j = 0; j < second.Length; j++)
if (first[i] * second[j] == output)
list.Add(first[i] + " x " + second[j] + " = " + output);
foreach (var str in list) {
Console.WriteLine(str);
}
}
}
See a live demonstration here
This code accepts user input (set to "8" for testing purposes) and will loop through the first array items and then loop through the second array.A multiplication is done for each item in the first by each item in the second using this nested loop logic.Hope this helped you in some way.
I would go for the double loop, as a couple of the other answers do.
In case you want to avoid a double loop (for some particular reason), it can be done without it. In Java:
int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// not using b
int x = 8;
for (int firstFactor : a) {
if (firstFactor != 0 && x % firstFactor == 0) {
int secondFactor = x / firstFactor;
if (0 <= secondFactor && secondFactor <= 9 && secondFactor != firstFactor) {
System.out.println("" + firstFactor + " * " + secondFactor);
}
}
}
The code above does not work for x equal to 0, you would have to treat this case specially (which you don’t have to in the double loop approach). For x equal to 8 the code prints:
1 * 8
2 * 4
4 * 2
8 * 1
I suggest using Linq while avoiding Cartesian Join (what if A and B are large?):
int[] A = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] B = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int goal = 10;
var result = A
.Where(a => a != 0 && goal % a == 0) // a from A is divider of the goal
.Where(goal / a != a) // a and b can't be the same
.Where(a => B.Contains(goal / a)) // b is in B
.OrderBy(a => a) // let be nice
.Select(a => string.Format("{0} {1}", a, goal / a));
Test
Console.Write(string.Join(Environment.NewLine, result));
Outcome
2 5
5 2
Stress test:
int[] A = Enumerable.Range(0, 1000000).ToArray();
int[] B = Enumerable.Range(0, 1000000).ToArray();
int goal = 2016;
will return within milliseconds
1 2016
2 1008
3 672
4 504
6 336
7 288
8 252
9 224
...
504 4
672 3
1008 2
2016 1
You have an array that represents a line of servers by their "Down-time cost". You can only access servers at either end of the line (i.e You can only get the first server or the last server).
The order at which a server is picked is multiplied with it's downtime and added to a "total downtime cost".
Design a program to find the least total downtime cost.
For example, for the array:
[5, 3, 6, 2, 1, 4]
the least total downtime is:
5*1 + 4*2 + 3*3 + 6*4 + 2*5 + 1*6 = 62
This is the code that I use for getting this result:
public static void main(String[] args){
int[] serverDowntimes = {5, 3, 6, 2, 1, 4};
int start = 0;
int end = serverDowntimes.length - 1;
long totalCost = 0;
int serverNumber = 1;
while(start <= end){
if(serverDowntimes[start] >= serverDowntimes[end]){
totalCost += serverNumber * serverDowntimes[start];
start++; //Increment start (i.e. First server in line was recovered)
}else{
totalCost += serverNumber * serverDowntimes[end];
end--; //Decrement end (i.e. Last server in line was recovered)
}
serverNumber++;
}
System.out.println(totalCost);
}
However my code fails when I have this array:
[5, 3, 1, 8, 2, 4]
For this array my code outputs:
76 (5*1 + 4*2 + 3*3 + 2*4 + 8*5 + 1*6)
However the better answer should be:
73 (4*1 + 2*2 + 8*3 + 5*4 + 3*5 + 1*6)
How do I modify my code so that it also works with the arrays similar to:
[5, 3, 1, 8, 2, 4]
I wrote brute-force algorithm that tests every possible solution and picks the best.
For following problem set:
[5, 3, 1, 8, 2, 4]
It generates solution of:
lowest cost: 72, with combination: [5, 4, 2, 8, 3, 1]
Which we can prove by calculating:
5*1 + 4*2 + 2*3 + 8*4 + 3*5 + 1*6 = 72
Here's the solver:
import java.util.*;
class ServersProblemSolver {
public static void main(String[] args) {
int[] serverDowntimes = {5, 3, 1, 8, 2, 4};
int totalCost = Integer.MAX_VALUE;
List<Integer> bestCombination = new ArrayList<>();
for (int i = 0; i < Math.pow(2, serverDowntimes.length); i++) {
int temporaryCost = 0;
int combination = i;
int start = 0;
int end = serverDowntimes.length - 1;
List<Integer> temporaryCombination = new ArrayList<>();
for (int k = 0; k < serverDowntimes.length; k++) {
if (combination % 2 == 1) {
temporaryCost += (k + 1) * serverDowntimes[start];
temporaryCombination.add(serverDowntimes[start]);
start++;
} else {
temporaryCost += (k + 1) * serverDowntimes[end];
temporaryCombination.add(serverDowntimes[end]);
end--;
}
combination /= 2;
}
System.out.println("combination " + i + ": " + temporaryCombination + ", cost : " + temporaryCost);
if (temporaryCost < totalCost) {
totalCost = temporaryCost;
bestCombination = temporaryCombination;
} else {
temporaryCombination.clear();
}
}
System.out.println("lowest cost: " + totalCost + ", with combination: " + bestCombination);
}
}
How does it work?
Take every binary combination between 0 and 2 ^ N, where N is the size of your array.
Pick a server from start or end according to succesive binary digit (whether it's 0 or 1)
101 will take start, end, start
000 will take end, end, end
110 will take end, start, start
etc.
After calculating the result of current combination, check if it's better than the previous best, and if so, save it.
Note: This has been solved. I have posted the working code below in a later post.
First off, I know there is a similar question here: Pick four cards and compute their sum JAVA
However, the outcome of their script is different than what mine needs to be, they are just calculating 4 random cards. I need to find EVERY combination of 4 cards that exists.
I am currently in my first Java programming class. We have covered up to methods and arrays, but nothing about classes and objects yet. So please keep that in mind if you choose to answer.
My homework this week is to write a program that finds every possible combination of 4 cards in a deck of 52 that add up to 24. (with Ace being 1, Jack 11, Queen 12, and King 13) I have posted my code below which I know has some mistakes, it doesn't work right for how I want it to. I am posting here to see if I'm on the right track. My instructor says the correct answer is 12,517, and it's up to us to come up with that answer. Any hints would be greatly appreciated.
Specific Question as requested - "How can I change my below code that will produce the output of 12,517"
Things I know:
I know some numbers are missing in the iterations, the 4th stack resets back to 4 instead of going to 1. I haven't yet figured out how to correct this.
I know my deepest For loop will loop the same combination 4 times before continuing... I have NO idea why (or how) it's doing this.
NOTE!: I have output messages in the "calculate" method for debugging. If you want to use them, start then stop the script immediately, that will give you an idea. If you want the program to run till completion, then comment out the 3 output messages in the nested 4 loop.
public static void main(String[] args) {
int[] deck = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
int total;
total = calculate(deck);
output(total);
}
public static int calculate(int[] deck){
int total = 0;
int stack1, stack2, stack3, stack4, accumulate;
for (stack1 = 0; stack1 < 52; stack1++){
for (stack2 = 1; stack2 < 52; stack2++){
for (stack3 = 2; stack3 < 52; stack3++){
for (stack4 = 3; stack4 < 52; stack4++){
accumulate = (deck[stack1] + deck[stack2] + deck[stack3] + deck[stack4]);
System.out.println(deck[stack1] + " + " + deck[stack2] + " + " + deck[stack3] + " + " + deck[stack4]);
if (accumulate == 24){
System.out.println(deck[stack1] + " + " + deck[stack2] + " + " + deck[stack3] + " + " + deck[stack4]);
total++;
System.out.println("Accumulate is at " + accumulate);
System.out.println("Currently at " + total);
}
}
}
}
}
return total;
}
public static void output(int total){
System.out.println ("The total number of card combinations of 4 that \n"
+ "equal 24 is: " + total);
}
}
I would do it as such:
public static void main(String[] args) {
int counter = 0; //can also just say int counter; ==> auto intialize to 0
int d, c, h, s; //diamond, club, heart, spade
for(d = 1; d < 14; d++) //each suit starts at Ace, or the value of 1
for(c = 1; c < 14; c++) //each suit ends at 13, or King
for(h = 1; h < 14; h++)
for(s = 1; s < 14; s++)
if( d + c + h + s == 24 )
counter++;
System.out.println(counter); //Your total should be your instructor's 12,517
}
If I may clarify your question: You do NOT mean to ask for every single "combination" of cards (so printing out all 12,517 possibilities).
Rather, you mean to get the total number of combinations represented by counter.
What my four for loops are doing is very simple: it goes through all the possibilities using Ace as 1 and King as 13. If the sum of the four cards equals ( == ) 24, then add one to the counter.
This will work due to the nature of nested for loops, going through all four sets of 13C1 combinatorics.
I hope this helped!
NOTE: In case you weren't aware: in languages with brackets (Java, C), if you're using a conditional statement or a loop (if/else, while, for) with only one following statement, like in my code, you can omit the brackets.
Here is working code that produces the correct result. The key was to parent the child stack to the parent stack + 1:
public static void main(String[] args) {
int[] deck = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
int total;
total = calculate(deck);
output(total);
}
public static int calculate(int[] deck){
int total = 0;
int stack1, stack2, stack3, stack4, accumulate;
for (stack1 = 0; stack1 < 52; stack1++){
for (stack2 = (stack1 + 1); stack2 < 52; stack2++){
for (stack3 = (stack2 + 1); stack3 < 52; stack3++){
for (stack4 = (stack3 + 1); stack4 < 52; stack4++){
accumulate = (deck[stack1] + deck[stack2] + deck[stack3] + deck[stack4]);
if (accumulate == 24)
total++;
}
}
}
}
return total;
}
public static void output(int total){
System.out.println ("The total number of card combinations of 4 that \n"
+ "equal 24 is: " + total);
}
}