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.
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));
I am trying to make a program where I can input the size of a 2D array, the highest number in a 2D array, and the most amount of a certain number in the 2D array, and then fill it with random numbers in between 1 and the highest number. In my code, I specify that the max amount of times a number should repeat is 4, yet my output doesn't match that. Any suggestions?
This is my code:
class Main {
public static void main(String[] args) {
System.out.println(fill(6, 9, 4));
}
public static String fill(int size, int max, int most) {
int[][] list = new int[size][size];
int count = 0;
for (int i = 0; i < list.length; i++) {
for (int j = 0; j < list[i].length; j++) {
int x = (int)((Math.random()* max) + 1);
int y = 0;
count = 0;
for (int k = 0; k < list.length; k++) {
for (int l = 0; l < list[k].length; l++) {
if(list[k][l] == x) count++;
}
}
if(count < most) {
list[i][j] = x;
} else {
while(true) {
y = (int)((Math.random()* max) + 1);
if(y != x) break;
}
list[i][j] = y;
}
System.out.print(list[i][j] + " ");
}
System.out.println();
}
return "";
}
}
And this is my output:
9 4 6 1 9 1
7 1 4 4 3 2
6 1 4 2 7 9
5 9 4 7 2 5
3 5 3 5 7 4
3 8 8 6 2 6
Problem: There are 6 "4"s and 2 "8"s
You generate a random number.
You then check if this random number is 'invalid', in the sense that it's been used too many times.
Then, you generate a new random number, check that this isn't the same as your previous number, and then just roll with that. You are failing to check if this number, too, is 'overloaded'. So, what could have happened here is that your algorithm picked '9', counts 9s, finds 4 of them, rolls up a new random number, 9 again, so it rolls yet another number, 4, and just puts 4 in, without checking again.
Rejigger your while loops.
Or, better yet, make a utility class to offload the job of generating a random number, but not a number that's already been returned N times, to a separate class, so that you can untangle this messy code.
Your method
while(true) {
y = (int)((Math.random()* max) + 1);
if(y != x) break;
}
does not check that count of y did not already reached most
Your Issue is here:
while(true) {
y = (int)((Math.random()* max) + 1);
if(y != x) break;
}
list[i][j] = y;
This basically just rules out that x will be repeated more than most, but not y.
On a side note, I recommend using hash maps to keep track of the occurrences instead of iterating over the whole array over and over.
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];
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.
CS student here. I've just received an introduction to loops and I'm not sure I understand them very well. I'm trying to print a triangle of numbers n, such that if n = 4 you'd get something like this:
4
3 7
2 6 9
1 5 8 10
Instead I'm winding up with something like:
4
3 5
Suffice it to say I'm lost. Here's my code:
void drawT3 (int n)
{
int k = 1;
int t = 1;
for (int i=1;i<=n;i++)
{
k = n;
int j;
for (j=1;j<=n-i;j++)
System.out.print(" ");
for (j=1;j<=t;j++)
{
System.out.printf("%3d",k);
k += (n - j);
}
n--;
t++;
System.out.println();
}
}
void printTriangle(int n)
{
// build an auxiliary 2D array
final int t[][] = new int[n][n];
int i = 1;
for (int s = n - 1; s <= 2 * (n - 1); s++)
{
for (int x = s - n + 1; x < n; x++)
{
t[x][s - x] = i++;
}
}
// print the array
for (int y = 0; y < n; y++)
{
for (int x = 0; x < n; x++)
{
if (t[x][y] > 0)
{
System.out.printf("%3d", t[x][y]);
}
else
{
System.out.printf(" ");
}
}
System.out.println(); // start new line
}
}
Build an auxiliary 2D array of size n.
Put numbers into array as human will do, from 1 to n, following the diagonals. s in the code represents x + y sum. That sum is constant for every diagonal. In the first diagonal (the longest one) sum is equal to n - 1. In the second diagonal sum is 1 more, n. In the last "diagonal" (bottom right corner) the sum is 2 * (n - 1). That's exactly our loop: for (int s = n - 1; s <= 2 * (n - 1); s++). Having the sum and x we can obtain y with simple subtraction, y = s - x.
Print the array. Each cell of array is initialized with 0 (int's default value). So, if a cell has zero, we just print 3 spaces, to preserve the shape of triangle.
PS. My code was written for "educational purposes" :) To show how it can be done, in easy way. It's not optimized for speed nor memory.
public static void main(String[] args) {
// TODO code application logic here
triangle(4);
}
static public void triangle(int n){
int x = 0;
for (int i = n;i>0;i--){
System.out.print(i + " ");
x = i+n;
for (int j=0;j<n-i;j++){
System.out.print(x - j + " ");
x = x + n -j;
}
System.out.println("");
}
}
Output for 4:
4
3 7
2 6 9
1 5 8 10
Output for 6:
6
5 11
4 10 15
3 9 14 18
2 8 13 17 20
1 7 12 16 19 21
Observe that there are many ways to print out a triangle of numbers as described above, For example, here are two,
// for n=5,
// 1 2 3 4 5
// 6 7 8 9
// 10 11 12
// 13 14
// 15
And
// 5
// 4 9
// 3 8 12
// 2 7 11 14
// 1 6 10 13 15
And since recursion is Fun!
class triangle
{
//Use recursion,
static int rowUR( int count, int start, int depth )
{
int ndx;
if(count<=0) return start;
//-depth?
for (ndx=0;ndx<depth;ndx++)
{
System.out.print(" ");
}
//how many? 5-depth, 5,4,3,2,1
for( ndx=0; ndx<count; ++ndx )
{
System.out.printf("%3d",start+ndx);
}
System.out.printf("\n");
if( count>0 )
{
rowUR( count-1, ndx+start, depth+1 );
}
return ndx;
}
//Use recursion,
static int rowLR( int count, int start, int depth )
{
int ndx, accum;
if( start < count )
rowLR( count, start+1, depth+1 );
for( ndx=0; ndx<depth; ++ndx )
{
System.out.print(" ");
}
accum=start;
//how many? 5-depth, 1,2,3,4,5
for( ndx=0; ndx<(count-depth); ++ndx )
{
System.out.printf("%3d",accum);
accum+=count-ndx;
}
System.out.printf("\n");
return ndx;
}
public static void main(String[] args)
{
int count=4, depth=0, start=1;
System.out.printf("rowUR\n");
rowUR( count=5, start=1, depth=0 );
System.out.printf("rowLL\n");
rowLL( count=5, start=1, depth=0 );
}
};
int n=4,i,j,k,t;
for (i=n;i>=1;i--)
{
t=i;
k=n;
for(j=1;j<i;j++)
System.out.printf(" "); // for leading spaces
System.out.printf("%3d",i); // for first digit(or number) in each row (in your example these are 4,3,2,1)
for(j=i;j<n;j++)
{
t+=k;
System.out.printf("%3d",t);
k--;
}
System.out.print("\n");
}
OUTPUT:
for n=8
8
7 15
6 14 21
5 13 20 26
4 12 19 25 30
3 11 18 24 29 33
2 10 17 23 28 32 35
1 9 16 22 27 31 34 36
http://ideone.com/C1O1GS
make space around numbers according to your need.
PS: I would never suggest to write any pattern code using array unless it is very complicated. array will use extra memory space.