Related
I want to write a program that matches n men [0,1,2,...,n-1] to n women [0,1,2,...,n-1] according to their preferences. These preferences are represented by n x n-matrices, one for the men and one for the women.
[ 0 2 1 ]
E.g. men: [ 1 0 2 ]. The rows represent each man from 0 to 2, and per row we see a man's 'top 3'.
[ 1 2 0 ]
In this example: man 0 prefers woman 0 over woman 2; woman 1 is both man1's and man2's most prefered partner.
Now, I want to make sure that the matchings are as ideal as possible. This can be done by using the Gale-Shapley Algorithm.
I have two questions:
Suppose that m0 and m1 both have w0 as their first pick. Then, we'll have to look at w0's preferences: suppose that m0 is ranked higher, then (m0,w0) is a (temporary) matching. What should I do next? Do I first match m2 to his first pick, or - since m1 is still free - do I match m1 to his second pick?
I've already implemented an algorithm that looks like this:
Basically, the input consists of the preference matrices of both men and women. The result should be an array like res = [2,0,1], meaning man 2 is matched to woman 0, m0 with w1 and m1 with w2.
public int[] match(int[][] men, int[][] women) {
int n = men.length;
boolean[] menFree = new boolean[n];
Arrays.fill(menFree, true);
int[] res = new int[n];
Arrays.fill(res, -1);
int free = n;
int m = 0;
while (free > 0 && m<n) {
for (int i = 0; i < n; i++) {
if(menFree[i]){
int w = men[i][m];
if(res[w]==-1){
res[w]=i;
menFree[i]=false;
free--;
} else {
int c = res[w];
int colI = 0;
int colC = 0;
for(int j=0;j<n;j++){
if(women[w][j]==i){
colI = j;
} else if(women[w][j]==c){
colC = j;
}
}
if(colI<colC){
res[w]=i;
menFree[c]=true;
menFree[i]=false;
} else {
//do nothing or change column here, depending on answer to my first question.
}
}
}
}
m++;
}
return res;
}
As you can see I'm not sure what to do with the else-part when the position of a man's (=M's) competitor is higher then the position of M himself. Also, if it turns out that I should at that point look for M's second pick, how can I do this? There's still a possibility that I'll have to return to the first pick of the man after M.
Thanks for helping me out.
I read the wiki. And I implement myself.I think I understand it but my program is not beautiful.Just for communication.
package algorithm;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class GaleShapley {
public static void main(String[] args) {
int[][] men = {{1, 2, 0}, {0, 1, 2}, {2, 1, 0}};
int[][] women = {{1, 2, 0}, {0, 1, 2}, {2, 1, 0}};
int[] res = match(men, women);
for (int i : res)
System.out.println(i);
}
static int[] match(int[][] men, int[][] women) {
Map<Integer, Integer> temp = new HashMap<>();
int size = men.length;
boolean[] menFree = new boolean[size];
boolean[] womenFree = new boolean[size];
Arrays.fill(menFree, true);
Arrays.fill(womenFree, true);
ArrayList<Integer> stillFree = new ArrayList<>();
while (stillFree.size() + temp.size() < size) {
for (int i = 0, j = 0; i < size; i++, j = 0) {
if (menFree[i]) {
for (; j < size; j++) {
//if the woman is free,make them a pair
if (womenFree[men[i][j]]) {
// make woman and man i pair, the woman's index is men[i][j]
temp.put(men[i][j], i);
menFree[i] = false;
womenFree[men[i][j]] = false;
break;
} else {
// the woman is not free,check her pair is whether stable
int pairMan = temp.get(men[i][j]);
boolean stable = checkStable(pairMan, i, men[i][j], women);
// not stable break them and make new pair
if (!stable) {
temp.put(men[i][j], i);
menFree[i] = false;
menFree[pairMan] = true;
break;
}
}
}
// if man i is still free , it means that he can't find a woman
if (menFree[i])
stillFree.add(i);
}
}
}
int[] stablePair = new int[2 * temp.size()];
int i = 0;
for (Map.Entry<Integer, Integer> entry : temp.entrySet()) {
stablePair[i] = entry.getValue();
i++;
stablePair[i] = entry.getKey();
i++;
}
return stablePair;
}
static boolean checkStable(int pairMan, int currentMan, int woman, int[][] women) {
// index of pairMan and currentMan
int p = 0, c = 0;
for (int i = 0; i < women.length; i++) {
if (women[woman][i] == pairMan)
p = i;
else if (women[woman][i] == currentMan)
c = i;
}
// p<c : the woman love p more than c, they are stable
return p < c;
}
}
I have two questions:
public static int[] everyOther(int[] arr)
Given an integer array arr, create and return a new array that contains precisely the elements in the even-numbered positions in the array arr. Make sure that your method works correctly for arrays of both odd and even lengths, and for arrays that contain zero or only one element. The length of the result array that you return must be exactly right so that there are no extra zeros at the end of the array.
public static int[][] createZigZag(int rows, int cols, int start)
This method creates and returns a new two-dimensional integer array, which in Java is really just a one-dimensional array whose elements are one-dimensional arrays of type int[]. The returned array must have the correct number of rows that each have exactly cols columns. This array must contain the numbers start, start + 1, ..., start + (rows * cols - 1) in its rows in order, except that the elements in each odd-numbered row must be listed in descending order.
For example, when called with rows = 4, cols = 5 and start = 4, this method should create and return the two-dimensional array whose contents are
4 5 6 7 8
13 12 11 10 9
14 15 16 17 18
23 22 21 20 19
when displayed in the traditional matrix form that is more readable for the human than the more realistic form of a one-dimensional array whose elements are one-dimensional arrays of rows.
public static int[] everyOther(int[] arr){
for (int i = 0 ; i < aList.size() ; i+=2)
{
return( aList.get(i) + " ") ;
}
}
public static int[][] createZigZag(int rows, int cols, int start){
{
int evenRow = 0;
int oddRow = 1;
while (evenRow < rows)
{
for (int i = 0; i < cols; i++)
{
return(start[evenRow][i] + " ");
}
evenRow = evenRow + 2;
if(oddRow < rows)
{
for (int i = cols - 1; i >= 0; i--)
{
return(start[oddRow][i] + " ");
}
}
oddRow = oddRow + 2;
}
}
}
does this make sense?
Try this as an attempted solution to your exercise.
Notes:
If you copy paste this whole code, make sure your class file is named TestExample as is this one.
Inside main method are just some tests so that you see the output printed and you can verify it. You can ignore Arrays.toString(), it's just to print the int[] arrays to the screen in a better format.
Wherever you see final, you can ignore it or erase it (for now, that you still learn the language). In a simple first look, it means you don't intend to change this variable. After you proceed in learning the language, visit this again but this time consider that it "locks" the variable name to a specific reference inside the enclosing scope. It doesn't guarantee immutability of the value however except if it is a primitive value (int, long, float, double etc).
Notice that the arrays have to have been initialized (their dimensions) before you assign any value to a specific position of the array.
For the everyOther method, note that Java is zero-based in its indexing and thus in the array new int[] { 8, 9, 10, 11 }; your first odd-indexed value is 9 and the second is 11.
General advice: If you are now starting with a language, use an IDE like Eclipse (it's free & open source), IntelliJ (free) or NetBeans(free & open source). It would red-underline the errors in your code and (if configured) display warning messages as well for dangerous practices.
Code:
import java.util.Arrays;
public class TestExample
{
public static int[][] createZigZag(final int rows, final int cols, int start)
{
final int[][] array = new int[rows][cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
array[i][j] = start;
start++;
}
}
return array;
}
public static int[] everyOther(final int[] array)
{
int otherArrayLength;
if (array.length % 2 == 0)
{
otherArrayLength = array.length / 2;
}
else
{
otherArrayLength = array.length / 2 + 1;
}
final int[] otherArray = new int[otherArrayLength];
int count = 0;
for (int i = 0; i < array.length; i += 2)
{
otherArray[count] = i;
count++;
}
return otherArray;
}
public static void main(final String[] args)
{
final int[] testArray = new int[] { 0, 1, 2, 3, 4, 5, 6 };
final int[] everyOtherArray = everyOther(testArray);
System.out.println(Arrays.toString(everyOtherArray));
final int rows = 4;
final int cols = 5;
final int start = 4;
final int[][] zigzagArray = createZigZag(rows, cols, start);
for (int i = 0; i < rows; i++)
{
System.out.println(Arrays.toString(zigzagArray[i]));
}
}
}
I want to remove the duplicates by putting them in a new array but somehow I only get a first instance and a bunch of zeros.
Here is my code:
public class JavaApplication7 {
public static void main(String[] args) {
int[] arr = new int[] {1,1,2,2,2,2,3,4,5,6,7,8};
int[] res = removeD(arr);
for (int i = 0; i < res.length; i++) {
System.out.print(res[i] + " ");
}
}
public static int[] removeD(int[] ar) {
int[] tempa = new int[ar.length];
for (int i = 0; i < ar.length; i++) {
if (ar[i] == ar[i+1]) {
tempa[i] = ar[i];
return tempa;
}
}
return null;
}
}
expected: 1,2
result: 1,0,0,0,0,0,0....
why dont you make use of HashSet?
final int[] arr = new int[] { 1, 1, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8 };
final Set<Integer> set = new HashSet<>();
for (final int i : arr) {
// makes use of Integer's hashCode() and equals()
set.add(Integer.valueOf(i));
}
// primitive int array without zeros
final int[] newIntArray = new int[set.size()];
int counter = 0;
final Iterator<Integer> iterator = set.iterator();
while (iterator.hasNext()) {
newIntArray[counter] = iterator.next().intValue();
counter++;
}
for (final int i : newIntArray) {
System.out.println(i);
}
Edit
if you want your array to be ordered
final int[] arr = new int[] { 9, 9, 8, 8, 1, 1, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8 };
Set<Integer> set = new HashSet<>();
for (final int i : arr) {
// makes use of Integer's hashCode() and equals()
set.add(Integer.valueOf(i));
}
// priomitive int array without zeros
final int[] newIntArray = new int[set.size()];
int counter = 0;
// SetUtils.orderedSet(set) requires apache commons collections
set = SetUtils.orderedSet(set);
final Iterator<Integer> iterator = set.iterator();
while (iterator.hasNext()) {
newIntArray[counter] = iterator.next().intValue();
counter++;
}
for (final int i : newIntArray) {
System.out.println(i);
}
A couple of points to help you:
1) With this: for(int i =0; i<ar.length; i++){ - you will get an IndexOutOfBoundsException because you are checking [i+1]. Hint: it is only the last element that will cause this...
2) Because you're initialising the second array with the length of the original array, every non-duplicate will be a 0 in it, as each element is initialised with a 0 by default. So perhaps you need to find how many duplicates there are first, before setting the size.
3) As mentioned in the comments, you are returning the array once the first duplicate is found, so remove that and just return the array at the end of the method.
4) You will also get multiple 2s because when you check i with i+1, it will find 3 2s and update tempa with each of them, so you'll need to consider how to not to include duplicates you've already found - based on your expected result.
These points should help you get the result you desire - if I (or someone else) just handed you the answer, you wouldn't learn as much as if you researched it yourself.
Here:
int[] tempa = new int[ar.length];
That creates a new array with the same size as the incoming one. All slots in that array are initialized with 0s!
When you then put some non-0 values into the first slots, sure, those stick, but so do the 0s in all the later slots that you don't "touch".
Thus: you either have to use a data structure where you can dynamically add new elements (like List/ArrayList), or you have to first iterate the input array to determine the exact count of objects you need, to then create an appropriately sized array, to then fill that array.
Return statement
As both commenters said, you return from the method as soon as you find your first duplicate. To resolve that issue, move the return to the end of the method.
Index problems
You will then run into another issue, an ArrayIndexOutOfBoundsException because when you are checking your last item (i = ar.length - 1) which in your example would be 11 you are then comparing if ar[11] == ar[12] but ar has size 12 so index 12 is out of the bounds of the array. You could solve that by changing your exit condition of the for loop to i < ar.length - 1.
Zeros
The zeros in your current output come from the initialization. You initialize your tempa with int[ar.length] this means in the memory it will reserve space for 12 ints which are initialized with zero. You will have the same problem after resolving both issues above. Your output would look like this: 1 0 2 2 2 0 0 0 0 0 0 0. This is because you use the same index for tempa and ar. You could solve that problem in different ways. Using a List, Filtering the array afterwards, etc. It depends what you want to do exactly.
The code below has the two first issues solved:
public class JavaApplication7 {
public static void main(String[] args) {
int[] arr = new int[] { 1, 1, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8 };
int[] res = removeD(arr);
for (int i = 0; i < res.length; i++) {
System.out.print(res[i] + " ");
}
}
public static int[] removeD(int[] ar) {
int[] tempa = new int[ar.length];
for (int i = 0; i < ar.length - 1; i++) {
if (ar[i] == ar[i + 1]) {
tempa[i] = ar[i];
}
}
return tempa;
}
}
There were a some error mentioned already:
return exits the method.
with arr[i+1] the for condition should bei+1 < arr.length`.
the resulting array may be smaller.
So:
public static int[] removeD(int[] ar) {
// Arrays.sort(ar);
int uniqueCount = 0;
for (int i = 0; i < ar.length; ++i) {
if (i == 0 || ar[i] != ar[i - 1]) {
++uniqueCount;
}
}
int[] uniques = new int[uniqueCount];
int uniqueI = 0;
for (int i = 0; i < ar.length; ++i) {
if (i == 0 || ar[i] != ar[i - 1]) {
uniques[uniqueI] = arr[i];
++uniqueI;
}
}
return uniques;
}
This question already has answers here:
Make individual array values to single number in Python [closed]
(3 answers)
Closed 6 years ago.
Here is my array, it consists of array of integers. Actually, these are the key of my HashMap which consists of some sentences or say "STRING" of a complete paragraph as a key value pair. Now I wanted to join those sentences from taking the key from the integer array one after another in given order.
int[] arr = {3, 2, 0, 5, 3};
HashMap<Integer, String> h = new HashMap<Integer, String>() {{
put(0,"This is my third sentence.");
put(3,"This is my first sentence.");
put(5,"This is my forth sentence.");
put(2,"This is my second sentence.");
}};
The final output should be all the sentences combined as mentioned order and outout should be like a paragraph as :
This is my first sentence.This is my second sentence.This is my third sentence.
This is my forth sentence.This is my first sentence.
Instead of converting the value to a character type you can perform math. For each digit in the array, the corresponding power of 10 is the array length (minus one) minus the index (because Java arrays use 0 based indexing and the last digit corresponds to 100). Something like,
int[] arr = { 3, 2, 0, 5, 3 };
int result = 0;
for (int i = 0; i < arr.length; i++) {
result += arr[i] * Math.pow(10, arr.length - i - 1);
}
System.out.println(result);
Output is (as expected)
32053
Optimization
It's possible to optimize the code further by keeping the current power of ten and dividing 10 while iterating each digit. This would also allow the use of a for-each loop like
int[] arr = { 3, 2, 0, 5, 3 };
int result = 0;
int pow = (int) Math.pow(10, arr.length - 1);
for (int digit : arr) {
result += digit * pow;
pow /= 10;
}
System.out.println(result);
Alternatively, iterate the digits from right to left and multiply pow by 10 on each iteration. That might look something like,
int result = 0;
int pow = 1;
for (int i = arr.length - 1; i >= 0; i--) {
result += arr[i] * pow;
pow *= 10;
}
And the above might also be written like
int result = 0;
for (int i = arr.length - 1, pow = 1; i >= 0; i--, pow *= 10) {
result += arr[i] * pow;
}
int number = Integer.parseInt(Arrays.stream(arr).mapToObj(String::valueOf).collect(Collectors.joining()));
Yet another way:
int[] arr = {3, 2, 0, 5, 3};
int i = Integer.parseInt(Arrays.toString(arr).replaceAll("[\\[,\\] ]", ""));
System.out.println(i); // prints 32053
Though fairly simple, you should have tried yourself.
Still providing a solution, just debug and understand it.
Working Code
public static void main(String[] args) throws Exception {
int[] arr = {3, 2, 0, 5, 3};
StringBuilder numberStr = new StringBuilder();
for (int item : arr) {
numberStr.append(item);
}
int finalInt = Integer.parseInt(numberStr.toString());
System.out.println(finalInt);
}
Output
32053
First convert the array into string by appending elements one by one and the convert string into integer. Try this code:
public class NewClass63 {
public static void main(String args[]){
int[] arr = {3, 2, 0, 5, 3};
StringBuffer s = new StringBuffer();
for(int i=0;i<arr.length;i++){
s.append(arr[i]);
}
int x = Integer.parseInt(s.toString());
System.out.println(x);
}
}
int[] array = {3,2,0,5,3};
String x = "";
for(int i = 0;i<=array.length-1;i++){
x = x + String.valueOf(array[i]);
}
System.out.println(Integer.parseInt(x));
use a loop:
int[] arr = { 3, 2, 0, 5, 3 };
String itotal = "";
for (int i = 0; i < arr.length; i++)
{
itotal=itotal + String.valueOf(arr[i]);
}
int a = Integer.parseInt(itotal);
There exist various ways.
If I am right, hidden assumption is that the higher element of integer array matches with higher digit of result integer.
int[] arr = {3, 2, 0, 5, 3};
int result = 0;
int power = (int) Math.pow(10, arr.length-1);
for(int element : arr){
result += element * power;
power /= 10;
}
Easiest solution answer is this.
Assume, each alphabet in the example is a single digit.
Empty Array {} : Expected value = 0
{a}: Expected value = a
{a,b}: Expected value = 10*a + b
{a,b,c}: Expected value = 10 * (10*a + b) + c
Code: Test this is online java compiler IDE
public class ConvertDigitArrayToNumber {
public static void main(String[] args) {
int[] arr = {3, 2, 0, 5, 3};
int value = 0;
for (int i = 0; i < arr.length; i++) {
value = (10*value) + arr[i];
}
System.out.println(value);
}
}
This is actually simpler and better solution than the other ones.
Only simple multiplication and addition (No powers).
No String conversions
Please read the question before marking it as duplicate
I have written following code to remove duplicates from array without using Util classes but now I am stuck
public class RemoveDups{
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 3, 1, 4, 52, 1, 45, };
int temp;
for (int i : a) {
for (int j = 0; j < a.length - 1; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
a = removeDups(a);
for (int i : a) {
System.out.println(i);
}
}
private static int[] removeDups(int[] a) {
int[] result = new int[a.length];
int j = 0;
for (int i : a) {
if (!isExist(result, i)) {
result[j++] = i;
}
}
return result;
}
private static boolean isExist(int[] result, int i) {
for (int j : result) {
if (j == i) {
return true;
}
}
return false;
}
}
and now the output is
1
2
3
4
5
6
45
52
0
0
0
0
0
0
0
0
0
0
Here my problem is
My code is not working in case of 0s
I am not able to understand how sorting an array can reduce time of execution
Is there any way to remove elements from array without using Util classes I know one way to remove convert array into list and then remove but for that also we need Util classes is there any way to implement by myself.
Since the numbers you deal with are limited to a small range you can remove duplicates by a simple "counting sort": mark the numbers you have found in a set-like data structure and then go over the data structure. An array of boolean works just fine, for less memory usage you could create a basic bitset or hash table. If n is the number of elements in the array and m is the size of the range, this algorithm will have O(n+m) complexity.
private static int[] removeDups(int[] a, int maxA) {
boolean[] present = new boolean[maxA+1];
int countUnique = 0;
for (int i : a) {
if (!present[i]) {
countUnique++;
present[i] = true;
}
}
int[] result = new int[countUnique];
int j = 0;
for (int i=0; i<present.length; i++) {
if (present[i]) result[j++] = i;
}
return result;
}
I am not able to understand how sorting an array can reduce time of execution
In a sorted array you can detect duplicates in a single scan, taking O(n) time. Since sorting is faster than checking each pair - O(n log n) compared to O(n²) time complexity - it would be faster to sort the array instead of using the naive algorithm.
As you are making the result array of the same length as array a
so even if you put only unique items in it, rest of the blank items will have the duplicate values in them which is 0 for int array.
Sorting will not help you much, as you code is searching the whole array again and again for the duplicates. You need to change your logic for it.
You can put some negative value like -1 for all the array items first in result array and then you can easily create a new result array say finalResult array from it by removing all the negative values from it, It will also help you to remove all the zeroes.
In java , arrays are of fixed length. Once created, their size can't be changed.
So you created an array of size18.
Then after you applied your logic , some elements got deleted. But array size won't change. So even though there are only 8 elements after the duplicate removal, the rest 10 elements will be auto-filled with 0 to keep the size at 18.
Solution ?
Store the new list in another array whose size is 8 ( or whatever, calculate how big the new array should be)
Keep a new variable to point to the end of the last valid element, in this case the index of 52. Mind you the array will still have the 0 values, you just won't use them.
I am not able to understand how sorting an array can reduce time of execution
What ? You sort an array if you need it to be sorted. Nothing else. Some algorithm may require the array to be sorted or may work better if the array is sorted. Depends on where you are using the array. In your case, the sorting will not help.
As for your final question , you can definitely implement your own duplicate removal by searching if an element exists more than once and then deleting all the duplicates.
My code is not working in case of 0
There were no zeroes to begin with in your array. But because its an int[], after the duplicates are removed the remaining of the indexes are filled with 0. That's why you can see a lot of zeroes in your array. To get rid of those 0s, you need to create another array with a lesser size(size should be equal to the no. of unique numbers you've in your array, excluding 0).
If you can sort your array(I see that its already sorted), then you could either bring all the zeroes to the front or push them to the last. Based on that, you can iterate the array and get the index from where the actual values start in the array. And, then you could use Arrays.copyOfRange(array, from, to) to create a copy of the array only with the required elements.
try this
package naveed.workingfiles;
public class RemoveDups {
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 3, 1, 4, 52, 1, 45, };
removeDups(a);
}
private static void removeDups(int[] a) {
int[] result = new int[a.length];
int j = 0;
int count = 0;
for (int i : a) {
if (!isExist(result, i)) {
result[j++] = i;
count++;
}
}
System.out.println(count + "_____________");
for (int i=0;i<count;i++) {
System.out.println(result[i]);
}
// return result;
}
private static boolean isExist(int[] result, int i) {
for (int j : result) {
if (j == i) {
return true;
}
}
return false;
}
}
public class RemoveDups {
public static void main(String[] args) {
int[] a = { 1, 2, 0, 3, 1,0, 3, 6, 2};
removeDups(a);
}
private static void removeDups(int[] a) {
int[] result = new int[a.length];
int j = 0;
int count = 0;
boolean zeroExist = false;
for (int i : a) {
if(i==0 && !zeroExist){
result[j++] = i;
zeroExist = true;
count++;
}
if (!isExist(result, i)) {
result[j++] = i;
count++;
}
}
System.out.println(count + "_____________");
for (int i=0;i<count;i++) {
System.out.println(result[i]);
}
// return result;
}
private static boolean isExist(int[] result, int i) {
for (int j : result) {
if (j == i) {
return true;
}
}
return false;
}
}
// It works even Array contains 'Zero'
class Lab2 {
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 3, 1, 4, 52, 1, 45 };
removeDups(a);
}
private static void removeDups(int[] a) {
int[] result = new int[a.length];
int j = 0;
int count = 0;
for (int i : a) {
if (!isExist(result, i)) {
result[j++] = i;
count++;
}
}
System.out.println(count + "_____________");
for (int i = 0; i < count; i++) {
System.out.println(result[i]);
}
}
private static boolean isExist(int[] result, int i) {
for (int j : result) {
if (j == i) {
return true;
}
}
return false;
}
}