I've been writing code to get all combinations of elements from array, but I couldn't figure out how to do it. Can you guys give me some advice?
This is what I'm trying to do...
int[] num = {1, 2, 3, 4, 5};
int n = num.length;
int length = (n * (n - 1)) / 2;
int[] list = new int[length];
for (int j = 0; j < n - 1; j++) {
for (int p = 4;p < n; p--) {
for (int i = 0; (I < length); i++) {
list[i] = Math.abs(num[j] - num[j + p]);
}
p++;
}
}
My result list would look like this..
list = {1, 2, 3, 4, 1, 2, 3, 1, 2, 1};
Thank you in advance.
edit: I'm really sorry that I didn't post my question clearly. What I was trying to do is get the absolute value of subtracting each values from array.
ex) 1-2 , 1-3, 1-4, 1-5, 2-3, 2-4, 2-5, 3-4, 3-5, 4,5
for (int v : list) {
System.out.println(v);
}
output:
1
2
3
4
1
2
...
Do it as follows:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] num = { 1, 2, 3, 4, 5 };
int n = num.length;
int length = (n * (n - 1)) / 2;
int[] list = new int[length];
// Index counter for list[]
int c = 0;
for (int i = n - 1; i >= 0; i--) {
for (int j = 0; j < i; j++) {
list[c++] = num[j];
}
}
// Display
System.out.println(Arrays.toString(list));
}
}
Output:
[1, 2, 3, 4, 1, 2, 3, 1, 2, 1]
For any value n the following should work. The key is to base the termination point of the inner loop on the outer loop's termination point.
System.out.println(string);
int n = 5;
int[] num = {1, 2, 3, 4, 5};
int length = (n * (n - 1)) / 2;
int m = 0;
int[] list = new int[length];
for (int i = 1; i<n ; i++) {
for (int k = 1; k <= n-i; k++) {
list[m++] = num[k-1];
}
}
System.out.println(Arrays.toString(list));
Prints
1 2 3 4 1 2 3 1 2 1
Related
Given an integer S and an array arr[], the task is to find the minimum number of elements whose sum is S, such that an element of the array can be chosen only once to get sum S.
Example:
Input: arr[] = {25, 10, 5}, S = 30
Output: 2
Explanation:
Minimum possible solution is 2, (25+5)
Example:
Input: arr[] = {2, 1, 4, 3, 5, 6}, Sum= 6
Output: 1
Explanation:
Minimum possible solution is 1, (6)
I have found similar solution here but it says element of array can be used multiple times.
I have this code from the link which uses an array element multiple times, but how to restrict this to use only once?
static int Count(int S[], int m, int n)
{
int [][]table = new int[m + 1][n + 1];
// Loop to initialize the array
// as infinite in the row 0
for(int i = 1; i <= n; i++)
{
table[0][i] = Integer.MAX_VALUE - 1;
}
// Loop to find the solution
// by pre-computation for the
// sequence
for(int i = 1; i <= m; i++)
{
for(int j = 1; j <= n; j++)
{
if (S[i - 1] > j)
{
table[i][j] = table[i - 1][j];
}
else
{
// Minimum possible for the
// previous minimum value
// of the sequence
table[i][j] = Math.min(table[i - 1][j],
table[i][j - S[i - 1]] + 1);
}
}
}
return table[m][n];
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 9, 6, 5, 1 };
int m = arr.length;
System.out.print(Count(arr, m, 11));
}
The idiomatic approach for this is to loop backwards when updating the table of previous results.
static int minElementsForSum(int[] elems, int sum){
int[] minElems = new int[sum + 1];
for(int i = 1; i <= sum; i++) minElems[i] = Integer.MAX_VALUE;
for(int elem: elems)
for(int i = sum; i >= elem; i--)
if(minElems[i - elem] != Integer.MAX_VALUE)
minElems[i] = Math.min(minElems[i], minElems[i - elem] + 1);
return minElems[sum];
}
Demo
This post - "Java + Count duplicates from int array without using any Collection or another intermediate Array", was also a sample exercise in my book at school, but what I want to do is get the elements that has duplicates without sorting it.
What I did is I removed the duplicates of arrays first, to get only the unique elements and then I compare it to the original array and count how many times the element has been found. But the problem is it doesn't print the correct elements which has duplicates.
int[] num = {7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1};
the correct output should be: 7, 1, 4
but instead it outputs: 7, 6, 1
This is my codes:
//method for removing duplicates
public static int[] removeDuplicates(int[] n) {
int limit = n.length;
for(int i = 0; i < limit; i++) {
for(int j = i + 1; j < limit; j++) {
if(n[i] == n[j]) {
for(int k = j; k < limit - 1; k++) {
n[k] = n[k + 1];
}
limit--;
j--;
}
}
}
int[] uniqueValues = new int[limit];
for(int i = 0; i < uniqueValues.length; i++) {
uniqueValues[i] = n[i];
}
return uniqueValues;
}
//method for getting elements that has duplicates
public static int[] getDuplicatedElements(int[] n) {
int[] nCopy = n.clone();
int[] u = removeDuplicates(nCopy);
int count = 0;
int limit = u.length;
for(int i = 0; i < u.length; i++) {
for(int j = 0; j < n.length; j++) {
if(u[i] == n[j]) {
count++;
}
}
if(count == 1) {
for(int k = i; k < limit - 1; k++) {
u[k] = u[k + 1];
}
limit--;
}
count = 0;
}
int[] duplicated = new int[limit];
for(int i = 0; i < duplicated.length; i++) {
duplicated[i] = u[i];
}
return duplicated;
}
//main
public static void main(String[] args) {
int[] num = {7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1};
//printing original values
System.out.print(Arrays.toString(num));
System.out.println();
int[] a = getDuplicatedElements(num);
System.out.print("Elements with Duplicates: " + Arrays.toString(a));
}
What's the error in my codes here? Please help thanks...
You have two issues:
public static int[] getDuplicatedElements(int[] n) {
int[] nCopy = n.clone();
int[] u = removeDuplicates(nCopy);
System.out.println ("unique " + Arrays.toString (u));
int count = 0;
int limit = u.length;
for(int i = 0; i < limit; i++) { // you must use limit instead of u.length
// in order for the loop to terminate
for(int j = 0; j < n.length; j++) {
if(u[i] == n[j]) {
count++;
}
}
if(count == 1) {
for(int k = i; k < limit - 1; k++) {
u[k] = u[k + 1];
}
limit--;
i--; // you must decrement i after you find a unique element in u
// otherwise you'll be skipping elements in the u array
}
count = 0;
}
int[] duplicated = new int[limit];
for(int i = 0; i < duplicated.length; i++) {
duplicated[i] = u[i];
}
return duplicated;
}
With those fixes, you'll get the expected output:
Elements with Duplicates: [7, 1, 4]
It's fairly simple when using a stream
int[] num = {7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1};
List<Integer> list = Arrays.stream(num).boxed().collect(Collectors.toList());
list.stream().filter(i -> Collections.frequency(list, i) > 1)
.collect(Collectors.toSet()).forEach(System.out::println);
Lets say I input array {1,2,3,4} and I want to make a new one {1,2,3,4,4,3,2,1}.
import java.util.Scanner;
public class Task2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[4];
for(int i = 0; i < arr.length; i++){
System.out.println("Please enter number!");
arr[i]=sc.nextInt();
}
int[] actualArr = new int[arr.length*2];
for(int j = 0; j < arr.length; j++){
actualArr[j]=arr[j];
}
for (int k = arr.length - 1; k >= 0; k--) { //problem loop
actualArr[arr.length] = arr[k];
}
for (int g = 0; g < actualArr.length; g++) {
System.out.print(actualArr[g] + " ");
}
}
}
Why do I get 1 2 3 4 1 0 0 0 ? My int k starts from 3 but I get the [0] index from int[]arr which is 1 and not the last which is 4, also how can i copy the rest of the first array in reverse order?
Your problem is on this line insithe the for loop:
actualArr[arr.length] = arr[k];
arr.length will always be 4, so you will always update the 5th element (element at index 4 because arrays are zero-based in Java) in your actualArr array leaving the remaining slots of the array with the default int value 0. Look how actualArr changes on each iteration of that loop:
actualArr = {1, 2, 3, 4, 4, 0, 0, 0} // 1st iteration
actualArr = {1, 2, 3, 4, 3, 0, 0, 0} // 2nd iteration
actualArr = {1, 2, 3, 4, 2, 0, 0, 0} // 3rd iteration
actualArr = {1, 2, 3, 4, 1, 0, 0, 0} // 4th iteration and final output
You can do this to fill the array correctly:
for (int k = arr.length - 1; k >= 0; k--) {
actualArr[actualArr.length - k - 1] = arr[k];
}
The expression actualArr.length - k - 1 will result in a sequence from 4-7 filling the array as you want.
You may can define a new integer like z and z is initial for your new array (actualArr):
int[] actualArr = new int[arr.length*2];
int z=0;
for(int j = 0; j < arr.length; j++){
actualArr[z]=arr[j];
z++;
}
for (int k = arr.length-1 ; k >= 0; k--) { //problem loop
actualArr[z] = arr[k];
z++;
}
I have wrote a program to shift an int array left, but cannot find a way to move it right. Could you take a look at my code and comment if you have any ideas how how to "rotate" my array right based on the number of spaces (int x), as currently it only moves left. Thanks
public void makeRight(int x) {
int[] anArray = {0, 1, 2, 3, 4, 5};
int counter = 0;
while (counter < x) {
int temp = anArray[0];
for (int i = 0; i < anArray.length - 1; i++) {
anArray[i] = anArray[i + 1];
}
anArray[anArray.length - 1] = temp;
counter++;
}
for (int i = 0; i < anArray.length; i++){
System.out.print(anArray[i] + " ");
}
}
Rotate an array right
public void makeRight( int x )
{
int[] anArray =
{ 0, 1, 2, 3, 4, 5 };
int counter = 0;
while ( counter < x )
{
int temp = anArray[anArray.length - 1];
for ( int i = anArray.length - 1; i > 0; i-- )
{
anArray[i] = anArray[i - 1];
}
anArray[0] = temp;
counter++;
}
for ( int i = 0; i < anArray.length; i++ )
{
System.out.print( anArray[i] + " " );
}
}
while (counter < x) {
int temp = anArray[anArray.length - 1];
for (int i = anArray.length - 1; i > 0; i--) {
anArray[i] = anArray[i - 1];
}
anArray[0] = temp;
counter++;
}
in my opinion basically you had done on most of the parts to rotate an array (right).
Just that the concept of
anArray[i] = secondArray[(i + x) % anArray.length];
And
anArray[(i + x) % anArray.length] = secondArray[i];
is a bit different.
There would be something like this
int[] anArray = {0, 1, 2, 3, 4, 5};
//int counter = 0;
//int x = 2;
int[] secondArray = new int[anArray.length];
for (int i = 0; i < anArray.length; i++) {
secondArray[(i + x) % anArray.length] = anArray[i];
}
for (int i = 0; i < secondArray.length; i++){
System.out.print(secondArray[i] + " ");
}
As for how the "%" works, Codility - CyclicRotation this link should had a clear explanation.
Below function can help you
public static void rightRotateArray(int[] a, int requiredIterations) {
// right-rotate [a] by k moves
// totalActiveIterations by MOD
// => because every n(a.length) rotations ==> we receive the same array
int totalActiveIterations = requiredIterations % a.length;
for (int i = 0; i < totalActiveIterations; i++) {
// make lastElement as BKP temp
int temp = a[a.length - 1];
// make other elements => each one equal previous one [starting by lastElement]
for (int j = (a.length - 1); j >= 1; j--) {
a[j] = a[j - 1];
}
// make 1stElement equal to (BKP as temp = lastElement)
a[0] = temp;
}
}
Something like this should work
private void shiftArrayRight() {
int endElementvalue = element[element - 1];
int[] startElements = Arrays.copyOfRange(element, 0 , element.length - 1);
element[0] = endElementvalue;
for(int i = 0, x = 1; i < startElements.length; i++, x++) {
element[x] = startElements[i];
}
System.out.println(Arrays.toString(element);
}
The other answers are merely code dumps, with zero explanations. Here's an algorithm I came up with:
We rotate the array in place. Observe that the target position of every element is given by (index + k) modulo size. For range 0 to k - 1, we recursively swap each element with the one in its target position as long as the target position is greater than the current position. This is because since we are incrementally progressing from lower to higher indices, a smaller target index indicates that the corresponding element had already been swapped.
Example:
Rotate [1, 2, 3, 4, 5, 6] by 3
Index to target index:
0 to 3
1 to 4
2 to 5
3 to 0
4 to 1
5 to 2
swap(0, 3) => [4, 2, 3, 1, 5, 6]
swap(0, 0) => return
swap(1, 4) => [4, 5, 3, 1, 2, 6]
swap(1, 1) => return
swap(2, 5) => [4, 2, 6, 1, 2, 3]
swap(2, 2) => return
Done!
Another example:
Rotate [2, 3, 4, 1] by 1
Index to target index:
0 to 1
1 to 2
2 to 3
3 to 0
swap(0, 1) => [3, 2, 4, 1]
swap(0, 2) => [4, 2, 3, 1]
swap(0, 3) => [1, 2, 3, 4]
swap(3, 0) => return
Done!
Code:
static void rotateRight(int[] xs, int k) {
swap(0, 0, xs, k);
}
private static void swap(int original, int current, int[] xs, int k) {
int target = (original + k) % xs.length;
if (target > current) {
int tmp = xs[current];
xs[current] = xs[target];
xs[target] = tmp;
swap(target, current, xs, k);
}
}
public static List<int> rotateLeft(int d, List<int> arr)
{
int listSize = arr.Count();
int[] newArr = new int[listSize];
for(int oldIndex=0; oldIndex< listSize; oldIndex++)
{
int newIndex = (oldIndex + (listSize - d))% listSize;
newArr[newIndex] = arr[oldIndex];
}
List<int> newList = new List<int>(newArr);
return newList;
}
the easiest way is to use c++ 11 and above, in Codility test for Cyclicrotation.
imagine doing it in earlier versions, Duh!
#include <algorithm>
#include <iterator>
vector<int> solution(vector<int> &A, int K) {
if (A.size() == 0) {
return A;
}
for (int i=0;i<K;i++) {
//Create auciliary array
std::vector<int> aux(A.size());
//copy array to be rotated there by means of C++11
std::copy(std::begin(A), std::end(A), std::begin(aux));
//insert last element from aux to begining of the array
A.insert(A.begin(), aux.end()-1, aux.end());
//remove last element which is already become first
A.pop_back();
}
return A;
}
Just change the code like this
public void makeRight(int x) {
int[] anArray = {0, 1, 2, 3, 4, 5};
int counter = 0;
while(counter< x){
int temp = anArray[anArray.length - 1];
for (int i = anArray.length - 1; i > 0; i--) {
anArray[i] = anArray[i - 1];
}
anArray[0] = temp;
counter++;
}
for (int i = 0; i < anArray.length; i++)
System.out.print(anArray[i] + " ");
}
I am a bit stuck so if anyone has a spare moment it would be a great help for me. I am using eclipse and the program is compiling and running. but there is a runtime error.
in the array {2, 1, 1, 2, 3, 3, 2, 2, 2, 1} I want to print {2, 2, 2} which is the numbers with the highest repeating times in the array. What I am getting is:
0
1
0
0
3
0
2
2
0
Thank you guys and here is my code.
public class SameIndexInArray
{
public static void main(String[] args)
{
int[] array = {2, 1, 1, 2, 3, 3, 2, 2, 2, 1};
int[] subarray = new int[array.length]; //store the values should be {2, 2, 2}
int max = 1;
int total = 1;
for(int i=0; i<array.length-1; i++)
{
if(array[i] != array[i + 1])
{
max = 1;
}
else if(array[i] == array[i + 1])
{
max++;
total = max;
subarray[i] = array[i]; // here is the issue
}
System.out.println(subarray[i]);
}
//System.out.println(total);
}
}
You only store facultatively into subarray, so you should define a separate counter (let's say j) for subarray index counting, and say subarray[j++] = array[i]. And, you shouldn't output subarray for each index of array, so move that println into the second if clause.
see if this works
int[] array = {2, 1, 1, 2, 3, 3, 2, 2, 2, 1};
int frequency = 0;
int num = 0;
for(int i=0; i<array.length-1; i++)
{
int lfreq = 1;
int lnum = array[i];
while(array[i] == array[i+1]){
lfreq++;
i++;
}
if(lfreq >= frequency){
frequency = lfreq;
num = lnum;
}
}
int[] subarray = new int[frequency];
for(int i=0; i < frequency; i++)
subarray[i] = num;
System.out.println(Arrays.toString(subarray));
You need to use another index but "i"
you can't relate to 2 arrays with the same index
Your problem is that all values in subarray are initialized with 0 and you only edit the values when there is an actual sequence, starting with the second element.
The whole subarray is unneccessary. Just save the start index and the length of the subquery ;)
What I mean is something like this:
int[] array = {2, 1, 1, 2, 3, 3, 2, 2, 2, 1};
int startIndex = 0;
int length = 0;
int longestIndex = 0;
int longestLength = 0;
for(int i=0; i<array.length-1; i++)
{
if(array[i] != array[i + 1])
{
if (length > longestLength) {
longestLength = length;
longestIndex = startIndex;
}
startIndex = i;
length = 1;
}
else if(array[i] == array[i + 1])
{
length++;
}
}
if (length > longestLength) {
longestLength = length;
longestIndex = startIndex;
}
Now you that you know where your longest sequence starts and how long it is you can build your new array:
int[] sequence = new int[longestLength];
for (int i = 0; i < longestLength; i++) {
sequence[i] = array[i + startIndex];
}
Thats because you are inserting at an index position "i" into subarray.
For example,
The second time the loop runs.
array[1] == array[2] is true and
subarray[i] = array[i];
runs. So at this moment the contents of subarray is {0,1,0,0,0,0,0,0,0}. Note that arrays are initialized to 0 by default.
This is how you could do it.
int[] array = {2, 1, 1, 2, 3, 3, 2, 2, 2, 1};
//store the values should be {2, 2, 2}
int max = 1;
int total = 1;
int value = 0;
for(int i=0; i<array.length-1; i++)
{
if(array[i] != array[i + 1])
{
max = 1;
}
else if(array[i] == array[i + 1])
{
max++;
total = max;
value = array[i];
}
}
int[] subarray = new int[total];
for(int i=0; i<total; i++)
subarray[i] = value;
public static void main(String[] args) {
int[] ar = { 2, 1, 1, 2, 3, 3, 2, 2, 2, 1 };
int max=0,
maxStart=0,
count=1;
for(int i=1; i<ar.length; i++) {
if (ar[i-1] == ar[i]) {
count++;
if(count > max) {
max = count;
maxStart = i-count+1;
}
}else {
count=1;
}
}
System.out.println("Sub array begins from " + maxStart);
for(int i = maxStart; i < maxStart + max; i++) {
System.out.print(ar[i] + " ");
}
}