Find 3 duplicates next to each other - java

int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i] == arr[j] && i != j) {
return false;
}else count++;
}
} return (count == 3);
Task: Given an integer denoting the size of the array.Fill array with integers and return true if array contains duplicate 3 times next to each other.
This code does not Works fine. Given true if found duplicates 2 times.I need three times,and next to each other!! Some1 could help me please?!

What's about this:
for (int i = 0; i < arr.length - 2; i++) {
if (arr[i] == arr[i + 1] && arr[i] == arr[i + 2]) {
return true;
}
}
return false;

Solution using ArrayList to store the matching numbers,
int[] arryOne={1,2,3,4,4,4,5,5,5,6,6,7,7,7,8,9,9,9,19,19,19,21,21,30,45,10,10,10};
ArrayList<Integer> arryTwo=new ArrayList<Integer>();
for (int x=0;x<=arry.length-1;x++)
{
if(arryOne[x]==arryOne[x+1] && arryOne[x]==arryOne[x+2] && x!=arry.length-2)
{
arryTwo.add(arry[x]);
x=x+2;
}
}
System.out.println("The number which is repeating three times in the array is = ");
for (int valInArrayList: arryTwo)
{
System.out.print(valInArrayList + ", ");
}

for(int i=0;i<arr.length-2;i++){
if((arr[i]==arr[i+1])&& (arr[i]==arr[i+2])){
return true;
}
}
return false;
This way, we only check the array once, and this improve performances. What we do here in plain english is : "Check if a number is equal to the two following him", and we stop before going out of the array (this is what array.length-2 is for)
Ex: for an array of 6 numbers, we will check
[0,1,2]
[1,2,3]
[2,3,4]
[3,4,5]

Related

Arrays - summing neighbours of elements?

The question asks to write static method sumNeighbours which takes an array of integers as an argument and returns an array with the same number of elements as the original array such that each integer in the new array is the sum of its neighbours and itself in the original array.
e.g.
[10, 20, 30, 40]
will be
[30, 60, 90, 70]
30(10+20) 60(20+10+30) 90(30+20+40) 70(40+30)
Thanks. Here's the code I've done and it works, BUT only for SOME cases, not ALL. Can anyone recommend a more efficient way to approach this? Without hard-coding all those if's and else's for certain cases.
public static int[] sumNeighbours(int[] values) {
int[] list = new int[values.length];
for (int i=0; i<values.length; i++) {
if (values.length > 1) {
if (values[i] == values[0]) {
list[i] = values[i] + values[i+1];
}
else if (values[i] == values[values.length-1]) {
list[i] = values[i] + values[i-1];
}
else {
list[i] = values[i] + values[i-1] + values[i+1];
}
}
else {
list [i] = values[i];
}
}
return list;
}
First: your input may be null, so null check first and I guess return null in that case.
Second: after creating an array of the same size you need to iterate the input and for each index check two things:
If index is smaller than (length-1) add the element on the right
If the index is greater than 0 add the element on the left
Always add the element in the current index
Done?
Don't use values to check if the element is either first of last, use the indexes and also have a nullptr check. Your code will fail for cases like [30,30,30]
public static int[] sumNeighbours(int[] values) {
if (null == values)
return null;
int[] list = new int[values.length];
for (int i=0; i<values.length; i++) {
if (values.length > 1) {
if (i == 0) {
list[i] = values[i] + values[i+1];
}
else if (i == values.length-1) {
list[i] = values[i] + values[i-1];
}
else {
list[i] = values[i] + values[i-1] + values[i+1];
}
}
else {
list [i] = values[i];
}
}
return list;
}
More efficiency way if you remove your if blocks within your loop:
public static int[] sumNeighbours(final int[] values) {
if (null == values || 2 > values.length) {
return values;
}
final int len = values.length;
final int[] list = new int[len];
list[0] = values[0] + values[1];
list[len - 1] = values[len - 2] + values[len - 1];
for (int i = 1; i < len - 2; i++) {
list[i] = values[i - 1] + values[i] + values[i + 1];
}
return list;
}
You do not need summary 3 numbers on the edges.
Check this Out,
public static int[] sumNeighbours(int[] values) {
int[] list = new int[(values.length)];
for (int i=0; i<values.length; i++) {
if (values.length > 1) { //To Check if there are more than one values
if(i==0) //It will check if it is first element
{
list[i]=values[i]+values[i+1]; //Add First value and second value to place it in first location. As first location has only one Neighbor
}
else if (i==(values.length-1)) //TO check If its last value
{
list[i]=values[i]+values[i-1]; //As Last Location has only one Neighbor
}
else
{
list[i]=values[i]+values[i-1]+values[i+1]; //For All intermediate locations
}
}
}
return list;
}
Here's the code I've done and it works, BUT only for SOME cases, not ALL
Probably it's because you compare values rather than indices: if (values[i] == values[0]) must be if (i == 0) and if (values[i] == values[values.length-1]) must be if (i == values.length - 1).
And snippet with less code and null-check may looks as follows
public static int[] sumNeighbours(int[] input) {
if (input == null) {
return null;
}
int[] result = new int[input.length];
for (int i = 0; i < input.length; i++) {
int sum = input[i];
if (i > 0) {
sum += input[i - 1];
}
if (i < (input.length - 1)) {
sum += input[i + 1];
}
result[i] = sum;
}
return result;
}

dynamic programming - subset sum - reconstruct paths

Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum.
For example:
set = {1,2,5,7}
sum = 8
=> true
I actually solved the problem with this code:
public boolean isSubsetSum(int[] set, int sum) {
Arrays.sort(set);
boolean[][] memo = new boolean[set.length+1][sum+1];
for (int i = 0; i < memo.length; i++) {
memo[i][0] = true;
}
for (int i = 1; i < memo.length; i++) {
for (int j = 1; j < memo[i].length; j++) {
if (set[i-1] > j) {
memo[i][j] = memo[i-1][j];
} else {
memo[i][j] = memo[i-1][j] || memo[i-1][j-set[i-1]];
}
}
}
return memo[memo.length-1][memo[memo.length-1].length-1];
}
However, now I want to reconstruct all the possible combinations that form the given sum.
Is it possible to do that from my memoization matrix or do I have to do it differently?
Make a new DP table called take[i][j] which is boolean. It is true if you take the i-th element for subset sum j. You fill it concurrently with your normal memo table:
for (int i = 1; i < memo.length; i++) {
for (int j = 1; j < memo[i].length; j++) {
if (memo[i-1][j]){
//no need to take ith elements, first i-1 have sum j
take[i][j] = false;
memo[i][j] = true;
}
else if (j-set[i-1] >= 0 && memo[i-1][j-set[i-1]]){
//take ith element, and search for set of size j-set[i-1] in 1..i-1
take[i][j] = true;
memo[i][j] = true;
}
else{
//neither memo[i-1][j] or memo[i-1][j-set[i-1]] valid, so no way to make sum
take[i][j]=false;
memo[i][j]=false;
}
}
}
Finally, to reconstruct a solution, you start with:
int i =set.length
int j = sum
while (i>=0 && j>=0){
if (take[i][j]){
print(set[i])
j = j - set[i]
i=i-1
}
else{
i=i-1
}
}
You can generalize this for all sets of solutions.

Having trouble getting the rest of the numbers in an Array. Java

I'm having trouble in getting the rest of the numbers after I sum up the first 3 elements. This is the question that it asks me: "Write a method that takes an array. return true if the sum of the first three elements in the array is less than the sum of the rest of the elements of the array."
Therefore 5 5 5 5 2 2 should be false. Since the first 3 numbers sum are greater than the sum of 5 2 2. My program returns true for this question and I would appreciate any help.
public static boolean sumThree(int [] myArray)
{
int sum = 0;
for(int i = 0; i < myArray.length; i++)
{
sum += myArray[i];
}
int sumof3E = myArray[0] + myArray[1] + myArray[2];
if(sum > sumof3E)
{
return true;
}
else if(sumof3E < sum)
{
return false;
}
else
{
return false;
}
}
You shouldn't include the first three elements of the array. Those have to be exclusive of the summation.
Change the for loop control variable to this:
for (int i = 3; i < myArray.length; i++) {
sum += myArray[i];
}
Also, you should remove the else if block from your code, because it's redundant (the first if statement checks for that condition):
else if(sumof3E < sum)
{
return false;
}
Alternatively, with the help of java 8 features, you can shorten your code into one line:
public static boolean sumThree(int [] myArray){
return Arrays.stream(myArray).limit(3).sum() < Arrays.stream(myArray).skip(3).sum();
}
note - with the alternative solution you won't get IndexOutOfBoundsException even if the array being passed in is empty.
There are two issues in your code:
1) You don't verify that the Array even has 3 elements before you index into it, which will potentially cause errors.
2) You're summing the entire array and comparing it to the sum of the first three elements... in your loop try initializing i = 3 in the loop initialization (assuming the array has at least 4 elements)
Pseudo code:
public static boolean sumThree(int [] myArray)
{
if (myArray.length < 4) { return false; }
var first = myArray[0] + myArray[1] + myArray[2];
var rest = 0;
for(int i = 3; i<myArray.length; i++) {
rest += myArray[i];
}
return first < rest;
}
the sum loop need to be altered to start from index 2 and else if is not required.
public static boolean sumThree(int[] myArray) {
int sum = 0;
for (int i = 3; i < myArray.length; i++) {
sum += myArray[i];
}
int sumof3E = myArray[0] + myArray[1] + myArray[2];
if (sum > sumof3E) {
return true;
}
else {
return false;
}
}
for clarity make a two loop then use the conditional operator or known as ternary operator for using thee if..else easily
int sum1=0;
int sum2=0;
for(int i=0;i<=2;++i)
{
sum1+=myArray[i];
}
for(int i=3;i<myArray.length;++i)
{
sum2+=myArray[i];
}
boolean myBool = (sum1>sum2)?false:true;
return myBool;
There is no need to keep going through the whole array at a time when first sum becomes less than sum of rest:
int sumf3 =0;
int sumRest=0;
for (int i = 0; i < myArray.length; i++)
{
if (i < 3){
sumf3 += myArray[i];
} else {
sumRest += myArray[i];
}
if(sumf3 < sumRest ){
return true;
}
}
return false;
P.S. and no need to check size of array before loop as well.

How to determine if numbers in an array list if divisible by the numbers in another array list?

I am trying to determine if the numbers in an array list are divisiable by all of numbers in antoher arraylist. My code below outputs all of the numbers from the listdiv list that are disible by any divisors in the listdivisor. I would like to output the values that are divisible by all divisiors in the list not any of them. For example If I have listdiv = [1,2,3,,5,8] and listdivisor= [2,4]. the expected output should be 8 , but this code outputs 2 and 8 .
Thank you !your effort will be greatly appreciated!
for (int i = 0; i < listdiv.size(); i++) {
for (int c = 0; c < listdivisor.size(); c++) {
if (listdiv.get(i) % listdivisor.get(c) == 0) {
System.out.println("final results are : " + listdiv.get(i));
}
}
}
Other way with java 8:
List<Integer> collect = listdiv.stream().filter(p ->
listdivisor.stream().allMatch(d -> p % d == 0)
).collect(Collectors.toList());
Or better performance with parallelStream():
List<Integer> collect = listdiv.parallelStream().filter(p ->
listdivisor.parallelStream().allMatch(d -> p % d == 0)
).collect(Collectors.toList());
Your error appears to be caused by that you were counting a dividend as being divisible by all divisors upon hitting the first matching divisor. Instead, you need to add logic which keeps track of all divisors and ensures that each one works with a given dividend.
System.out.println("final results are: ");
for (int i=0; i < listdiv.size(); i++) {
boolean isDivisible = true;
for (int c=0; c < listdivisor.size(); c++) {
if (listdiv.get(i) % listdivisor.get(c) != 0) {
isDivisible = false;
break;
}
}
if (isDivisible) {
System.out.println(listdiv.get(i));
}
}
Your condition checks for values divisible by at least a single divisor, which is not what you want.
You need to check all the divisors before generating output :
for (int i = 0; i < listdiv.size(); i++) {
boolean divisible = true;
for (int c = 0; c < listdivisor.size() && divisible; c++) {
if (listdiv.get(i) % listdivisor.get(c) != 0) {
divisible = false;
}
}
if (divisible) {
System.out.println("final results are : " + listdiv.get(i));
}
}
In the below solution I continue the outer for loop when an element from the first list is not divisible to any in the second list. If no such case happens the println will get called.
outer:
for (int i = 0; i < listdiv.size(); i++) {
for (int c = 0; c < listdivisor.size(); c++) {
if (listdiv.get(i) % listdivisor.get(c) != 0) {
continue outer;
}
}
System.out.println("Found : " + listdiv.get(i));
}
This solution doesn't need any extra variables (such as a boolean to keep status of divisibility) and uses the less known loop labels
All the algorithms presented so far are O(N*M). It is possible to get O(N+M) by first finding the LCM of the first list and using that to filter the second list.
int thelcm = 1
for(int i : listdivisor) {
thelcm = lcm(thelcm, i);
}
ArrayList<Integer> result = new ArrayList<>();
for(int j : listdiv) {
if( j % thelcm == 0 ) {
result.put(j);
}
}
We can use Set for getting the expected output, I have modified your code,
Set<Integer> firstIteration = new HashSet<>();
Set<Integer> nextIteration = new HashSet<>();
for (int c = 0; c < divisors.size(); c++) {
for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(i) % divisors.get(c) == 0) {
if (c == 0) {
firstIteration.add(numbers.get(i));
} else {
nextIteration.add(numbers.get(i));
}
}
}
if (c != 0) {
// We will perform Set intersection here for each iteration
firstIteration.retainAll(nextIteration);
}
}
System.out.println(firstIteration);
Hope this will solve your issue

Completely stumped on a multiple loop Java program

The following is NOT a homework problem, it's just a set of problems that I've been working through for practice and I was wondering if anybody else could figure it out:
http://codingbat.com/prob/p159339
Return an array that contains exactly the same numbers as the given array, but rearranged so that every 3 is immediately followed by a 4. Do not move the 3's, but every other number may move. The array contains the same number of 3's and 4's, every 3 has a number after it that is not a 3 or 4, and a 3 appears in the array before any 4.
*SOLVED - here is my working code:
public int[] fix34(int...nums)
{
int[] returnArray = new int[nums.length];
//ASSIGN ARRAY
//We know that all 3's can't be moved, and after every 3 there
//will automatically be a 4
for(int i = 0; i<nums.length; i++)
{
if(nums[i] == 3)
{
returnArray[i] = 3;
returnArray[i+1] = 4;
}
}
//REBUILD ARRAY - UNMOVED INDEXES
//If a value was not moved/affected by the above, it will get placed into the array
//in the same position
for (int i = 0; i < nums.length; i++)
{
if (returnArray[i] != 3 && returnArray[i] != 4 && nums[i] != 3 && nums[i] != 4)
{
returnArray[i] = nums[i];
}
}
//REBUILD ARRAY - MOVED INDEXES
//changed values = 0 in returnArray, as a result, any time we hit a 0 we
//can simply assign the value that was in the 4's place in the nums array
OuterLoop: for (int i = 0; i < nums.length; i++)
{
if (returnArray[i] == 0)
{
for (int n = 0; n < returnArray.length; n++)
{
if (returnArray[n] == 4)
{
returnArray[i] = nums[n];
continue OuterLoop;
}
}
}
}
return returnArray;
}
I don't know java, but maybe I can help anyway. i dont want to give you the solution, but think of it like this:
you can move every number that isn't a 3. that's our only limit. that being said:
the only spots you need to change are the spots following 3s....so....every time you loop through, your program should be aware if it finds a spot after a 3 that isn't a 4....
it should also be aware if it finds any 4s not preceded by a 3......
during each loop, once it's found the location of each of those two things, you should know what to do.
Initialize all the variables
for(int i = 0; i<n-1; i++)
{
if(arr[i] == 3)
{
if(arr[i+1] == 4)
continue;
else
{
temp = 0;
while(arr[temp] != 4)
temp++;
//Write your own code here
}
//Complete the code
}
I have NOT provided the entire code. Try completing it as you said it was for your practice.
public int[] fix34(int[] nums) {
int[] arr = new int[nums.length];
int index = 0;
int tempVal= 0,j=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==3){
arr[i] = nums[i];
index=i+1;
tempVal = nums[i+1];
j=index;
while(j<nums.length){
if(j<nums.length && nums[j]==4){
//System.out.println(j+"\t="+nums[j]);
nums[j]=tempVal;
nums[index] = 4;
break;
}
j++;
}
tempVal=0;
index=0;
}else{
arr[i] = nums[i];
}
}
index =0;
for(int i=0;i<nums.length;i++){
if(nums[i]==3 && nums[i+1]==4){
i+=1;
}else if(nums[i]==4){
index = i;
j=index;
while(j<nums.length){
if(nums[j]==3 && nums[j+1]!=4){
arr[index] = nums[j+1];
arr[j+1] = 4;
}
j++;
}
}
}
return arr;
}
Here's mine: A little overkill, but is always right, anyways i make 2 additional arrays and I make 2 passes in the loop putting the correct elements in the correct places. See Logic Below.
public int[] fix34(int[] nums) {
int index1 = 0;
int index2 = 0;
int index3 = 0;
int[] only4 = fours(nums); //holds all 4's in nums
int[] misc = new int[count4(nums)]; //will hold numbers after 3
for(int a = 0; a < nums.length - 1; a++){
if(nums[a] == 3){
misc[index1] = nums[a + 1]; //get it for later use
index1++;
nums[a + 1] = only4[index2]; //now the number after 3 is a 4, from the
index2++; //only4 array
}
}
for(int b = 1; b < nums.length; b++){
if(nums[b] == 4 && nums[b - 1] != 3){ //finds misplaced 4's
nums[b] = misc[index3]; //replaces lone 4's with the
index3++; //right hand side of each 3 original values.
}
}
return nums;
}
public int count4(int[] nums){
int cnt = 0;
for(int e : nums){
if(e == 4){
cnt++;
}
}
return cnt;
}
public int[] fours(int[] nums){
int index = 0;
int[] onlyFours = new int[count4(nums)]; //must set length
for(int e : nums){
if(e == 4){
onlyFours[index] = e;
index++;
}
}
return onlyFours;
}
I solved mine using two ArrayLists which contain the places of 3's and 4's.
I hope this helps.
public int[] fix34(int[] nums)
{
//Create a copy of nums to manipulate.
int[] ret = nums;
//Create two ArrayLists which carry corresponding places of 3 and 4;
ArrayList<Integer> threePositions = new ArrayList<Integer>();
ArrayList<Integer> fourPositions = new ArrayList<Integer>();
//Get the places of 3 and 4 and put them in the respective ArrayLists.
for (int i = 0; i < ret.length; i++)
{
if (ret[i] == 3)
{
threePositions.add(i);
}
if (ret[i] == 4)
{
fourPositions.add(i);
}
}
//Swap all ints right after the 3 with one of the 4s by using the referenced
//ArrayLists values.
for (int i = 0; i < threePositions.size(); i++)
{
int temp = ret[threePositions.get(i) + 1];
ret[threePositions.get(i) + 1] = ret[fourPositions.get(i)];
ret[fourPositions.get(i)] = temp;
}
//Return the ret array.
return ret;
}

Categories