How to check if an array has two different pairs of matching values?
Since you haven't actually tried any code, I'll give a description of how to solve this problem, but no actual code.
Start with a boolean
like pairFound
that's initialized to false
and change to true
when you find your first pair
. Additionally, you'll need an int
(pairValue
to keep track of the value of the first pair found (if you found one).
Iterate through, looking for a pair. If you find a pair, and pairFound
is false, set pairFound
to true
, and set pairValue
to the value of your first found pair
. Now keep iterating through.
If you find a pair and pairFound
is true
and the pair is != pairValue
, then return true;
. If you iterate through everything and haven't returned true
yet, then you can return false
.
Based on your updated question, you're pretty close.
boolean pairFound = false;
int pairValue = Integer.MIN_VALUE;
//or some value that arrayOfInts will never have based on context
for(int s = 0; s < arrayOfInts.length - 1; s++){
if(arrayOfInts[s] == pairValue) {
continue;
}
for(int c = s + 1; c < arrayOfInts.length; c++){
if(arrayOfInts[s] == arrayOfInts[c]) {
if(arrayOfInts[s] != pairValue) {
if(pairFound) {
return true;
}
pairValue = arrayOfInts[s];
pairFound = true;
break;
}
}
}
}
return false;
How can I find matching values in two arrays?
Naturally, my approach was to loop through the first array once and check the index of each value in the second array. If the index is > -1
, then push
it onto the returned array.
Array.prototype.diff = function(arr2) {
var ret = [];
for(var i in this) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};
My solution doesn't use two loops like others do so it may run a bit faster. If you want to avoid using for..in
, you can sort both arrays first to reindex all their values:
Array.prototype.diff = function(arr2) {
var ret = [];
this.sort();
arr2.sort();
for(var i = 0; i < this.length; i += 1) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};
Usage would look like:
var array1 = ["cat", "sum","fun", "run", "hut"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];
console.log(array1.diff(array2));
If you have an issue/problem with extending the Array prototype, you could easily change this to a function.
var diff = function(arr, arr2) {
And you'd change anywhere where the func originally said this
to arr2
.
Comparing two arrays of objects, and exclude the elements who match values into new array in JS
Just using the Array iteration methods built into JS is fine for this:
var result1 = [ {id:1, name:'Sandra', type:'user', username:'sandra'}, {id:2, name:'John', type:'admin', username:'johnny2'}, {id:3, name:'Peter', type:'user', username:'pete'}, {id:4, name:'Bobby', type:'user', username:'be_bob'}];
var result2 = [ {id:2, name:'John', email:'johnny@example.com'}, {id:4, name:'Bobby', email:'bobby@example.com'}];
var props = ['id', 'name'];
var result = result1.filter(function(o1){ // filter out (!) items in result2 return !result2.some(function(o2){ return o1.id === o2.id; // assumes unique id });}).map(function(o){ // use reduce to make objects with only the required properties // and map to apply this to the filtered array as a whole return props.reduce(function(newo, name){ newo[name] = o[name]; return newo; }, {});});
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) + '</pre>';
comparing elements of the same array in java
First things first, you need to loop to < a.length
rather than a.length - 1
. As this is strictly less than you need to include the upper bound.
So, to check all pairs of elements you can do:
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] != a[k]) {
//do stuff
}
}
}
But this will compare, for example a[2]
to a[3]
and then a[3]
to a[2]
. Given that you are checking !=
this seems wasteful.
A better approach would be to compare each element i
to the rest of the array:
for (int i = 0; i < a.length; i++) {
for (int k = i + 1; k < a.length; k++) {
if (a[i] != a[k]) {
//do stuff
}
}
}
So if you have the indices [1...5] the comparison would go
1 -> 2
1 -> 3
1 -> 4
1 -> 5
2 -> 3
2 -> 4
2 -> 5
3 -> 4
3 -> 5
4 -> 5
So you see pairs aren't repeated. Think of a circle of people all needing to shake hands with each other.
How to know if two arrays have the same values
Sort the arrays and compare their values one by one.
function arrayCompare(_arr1, _arr2) {
if (
!Array.isArray(_arr1)
|| !Array.isArray(_arr2)
|| _arr1.length !== _arr2.length
) {
return false;
}
// .concat() to not mutate arguments
const arr1 = _arr1.concat().sort();
const arr2 = _arr2.concat().sort();
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
Merge two array of objects based on a key
You can do it like this -
let arr1 = [ { id: "abdc4051", date: "2017-01-24" }, { id: "abdc4052", date: "2017-01-22" }];
let arr2 = [ { id: "abdc4051", name: "ab" }, { id: "abdc4052", name: "abc" }];
let arr3 = arr1.map((item, i) => Object.assign({}, item, arr2[i]));
console.log(arr3);
How to return 2 values from a Java method?
Instead of returning an array that contains the two values or using a generic Pair
class, consider creating a class that represents the result that you want to return, and return an instance of that class. Give the class a meaningful name. The benefits of this approach over using an array are type safety and it will make your program much easier to understand.
Note: A generic Pair
class, as proposed in some of the other answers here, also gives you type safety, but doesn't convey what the result represents.
Example (which doesn't use really meaningful names):
final class MyResult {
private final int first;
private final int second;
public MyResult(int first, int second) {
this.first = first;
this.second = second;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
}
// ...
public static MyResult something() {
int number1 = 1;
int number2 = 2;
return new MyResult(number1, number2);
}
public static void main(String[] args) {
MyResult result = something();
System.out.println(result.getFirst() + result.getSecond());
}
Related Topics
Codility Tape Equilibrium Getting Zero on Some Cases
Array Pairwise Matching in Java Give Error Also Store Data Between Two Similar Element
Set Drawable Size Programmatically
How to Create Multiple Objects Through Loops in Java
Way to Check If Two Collections Contain the Same Elements, Independent of Order
How to Get an Http Response Body as a String
Search Particular Column Value from CSV File Using Java
Spring Data Repository @Query - Update and Return Modified Entity
How to Find Out the Exact Requested Url in Servletrequest If That Url Contains Path Variables
How to Remove the Slashes from Json Key While Converting Object into String
How to Externalize Application.Properties in Tomcat Webserver for Spring
Detecting a File Downloaded in Selenium Java
Find Duplicate Objects Based on Property in Java