I want to make an application to find differences between two strings. How do I solve this?
st = "this is a cat.this is my cat."
st1 = "this is cat. this my cat."
The output should be "a is" as the missing words.
Here is my code
#SuppressLint("DefaultLocale")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String st="this is a cat. this is my cat.";
TextView tv1=(TextView) findViewById(R.id.textView2);
String st1="This is cat. this my cat.";
String blank="";
if(st.toLowerCase().contains(st1.toLowerCase()))
{
st=st.toLowerCase().replace(st1.toLowerCase(), blank);
tv1.setText(st);
}
}
You need a sort of DIFF function.
Check these answers:
Extract the difference between two strings in Java
How to perform string Diffs in Java?
You could use StringUtils.differences, it's the source:
6020 public static String difference(String str1, String str2) {
6021 if (str1 == null) {
6022 return str2;
6023 }
6024 if (str2 == null) {
6025 return str1;
6026 }
6027 int at = indexOfDifference(str1, str2);
6028 if (at == INDEX_NOT_FOUND) {
6029 return EMPTY;
6030 }
6031 return str2.substring(at);
6032 }
6033
6034 /**
6035 * <p>Compares two Strings, and returns the index at which the
6036 * Strings begin to differ.</p>
6037 *
6038 * <p>For example,
6039 * <code>indexOfDifference("i am a machine", "i am a robot") -> 7</code></p>
6040 *
6041 * <pre>
6042 * StringUtils.indexOfDifference(null, null) = -1
6043 * StringUtils.indexOfDifference("", "") = -1
6044 * StringUtils.indexOfDifference("", "abc") = 0
6045 * StringUtils.indexOfDifference("abc", "") = 0
6046 * StringUtils.indexOfDifference("abc", "abc") = -1
6047 * StringUtils.indexOfDifference("ab", "abxyz") = 2
6048 * StringUtils.indexOfDifference("abcde", "abxyz") = 2
6049 * StringUtils.indexOfDifference("abcde", "xyz") = 0
6050 * </pre>
6051 *
6052 * #param str1 the first String, may be null
6053 * #param str2 the second String, may be null
6054 * #return the index where str2 and str1 begin to differ; -1 if they are equal
6055 * #since 2.0
6056 */
6057 public static int indexOfDifference(String str1, String str2) {
6058 if (str1 == str2) {
6059 return INDEX_NOT_FOUND;
6060 }
6061 if (str1 == null || str2 == null) {
6062 return 0;
6063 }
6064 int i;
6065 for (i = 0; i < str1.length() && i < str2.length(); ++i) {
6066 if (str1.charAt(i) != str2.charAt(i)) {
6067 break;
6068 }
6069 }
6070 if (i < str2.length() || i < str1.length()) {
6071 return i;
6072 }
6073 return INDEX_NOT_FOUND;
6074 }
6075
6076 /**
6077 * <p>Compares all Strings in an array and returns the index at which the
6078 * Strings begin to differ.</p>
6079 *
6080 * <p>For example,
6081 * <code>indexOfDifference(new String[] {"i am a machine", "i am a robot"}) -> 7</code></p>
6082 *
6083 * <pre>
6084 * StringUtils.indexOfDifference(null) = -1
6085 * StringUtils.indexOfDifference(new String[] {}) = -1
6086 * StringUtils.indexOfDifference(new String[] {"abc"}) = -1
6087 * StringUtils.indexOfDifference(new String[] {null, null}) = -1
6088 * StringUtils.indexOfDifference(new String[] {"", ""}) = -1
6089 * StringUtils.indexOfDifference(new String[] {"", null}) = 0
6090 * StringUtils.indexOfDifference(new String[] {"abc", null, null}) = 0
6091 * StringUtils.indexOfDifference(new String[] {null, null, "abc"}) = 0
6092 * StringUtils.indexOfDifference(new String[] {"", "abc"}) = 0
6093 * StringUtils.indexOfDifference(new String[] {"abc", ""}) = 0
6094 * StringUtils.indexOfDifference(new String[] {"abc", "abc"}) = -1
6095 * StringUtils.indexOfDifference(new String[] {"abc", "a"}) = 1
6096 * StringUtils.indexOfDifference(new String[] {"ab", "abxyz"}) = 2
6097 * StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"}) = 2
6098 * StringUtils.indexOfDifference(new String[] {"abcde", "xyz"}) = 0
6099 * StringUtils.indexOfDifference(new String[] {"xyz", "abcde"}) = 0
6100 * StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"}) = 7
6101 * </pre>
6102 *
6103 * #param strs array of strings, entries may be null
6104 * #return the index where the strings begin to differ; -1 if they are all equal
6105 * #since 2.4
6106 */
6107 public static int indexOfDifference(String[] strs) {
6108 if (strs == null || strs.length <= 1) {
6109 return INDEX_NOT_FOUND;
6110 }
6111 boolean anyStringNull = false;
6112 boolean allStringsNull = true;
6113 int arrayLen = strs.length;
6114 int shortestStrLen = Integer.MAX_VALUE;
6115 int longestStrLen = 0;
6116
6117 // find the min and max string lengths; this avoids checking to make
6118 // sure we are not exceeding the length of the string each time through
6119 // the bottom loop.
6120 for (int i = 0; i < arrayLen; i++) {
6121 if (strs[i] == null) {
6122 anyStringNull = true;
6123 shortestStrLen = 0;
6124 } else {
6125 allStringsNull = false;
6126 shortestStrLen = Math.min(strs[i].length(), shortestStrLen);
6127 longestStrLen = Math.max(strs[i].length(), longestStrLen);
6128 }
6129 }
6130
6131 // handle lists containing all nulls or all empty strings
6132 if (allStringsNull || (longestStrLen == 0 && !anyStringNull)) {
6133 return INDEX_NOT_FOUND;
6134 }
6135
6136 // handle lists containing some nulls or some empty strings
6137 if (shortestStrLen == 0) {
6138 return 0;
6139 }
6140
6141 // find the position with the first difference across all strings
6142 int firstDiff = -1;
6143 for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) {
6144 char comparisonChar = strs[0].charAt(stringPos);
6145 for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) {
6146 if (strs[arrayPos].charAt(stringPos) != comparisonChar) {
6147 firstDiff = stringPos;
6148 break;
6149 }
6150 }
6151 if (firstDiff != -1) {
6152 break;
6153 }
6154 }
6155
6156 if (firstDiff == -1 && shortestStrLen != longestStrLen) {
6157 // we compared all of the characters up to the length of the
6158 // shortest string and didn't find a match, but the string lengths
6159 // vary, so return the length of the shortest string.
6160 return shortestStrLen;
6161 }
6162 return firstDiff;
6163 }
then
difference("this is a cat.this is my cat.", "this is cat. this my cat.");
You could just implement this methods, or the entire library if you need more methods from this library.
Documentation here.
The easy way is to split the both strings on the bases of spaces.
e.g
String[] separated_st = st.split(" ");
String[] separated_st1 = st1.split(" ");
now you have two arrays. loop through them and find what is missing and what is not.
Alternatively you can use StringTokenizer class.
Hope this will help.
Try this one.
import java.awt.List;
import java.util.ArrayList;
import java.util.Arrays;
public class Classwithoutnewkeyword {
public static void main(String args[]) {
try {
String s1 = "this is a cat.this is my cat.";
String s2 = "this is cat. this my cat."
String arr1[] = s1.split(" ");
String arr2[] = s2.split(" ");
java.util.List<String> list1 = new ArrayList<String>(
Arrays.asList(arr1));
java.util.List<String> list2 = new ArrayList<String>(
Arrays.asList(arr2));
ArrayList<String> tmp1 = new ArrayList<String>();
ArrayList<String> tmp2 = new ArrayList<String>();
for (int i = 0; i < arr1.length; i++) {
int k = 0;
for (int j = 0; j < arr2.length; j++) {
if (arr1[i].equalsIgnoreCase(arr2[j])) {
tmp1.add(arr1[i]);
} else {
tmp2.add(arr1[i]);
}
}
}
for (String strs : tmp1) {
list1.remove(strs);
}
System.out.print(list1.toString());
}catch(Exception e)
{
e.printStackTrace();
}
}
}
Сorrect solution is given below:
import java.util.ArrayList;
public class Classwithoutnewkeyword {
public static void main(String args[]) {
try {
String s1 = "this is a cat. this is my cat.";
String s2 = "this is cat. my cat.";
String arr1[] = s1.split(" ");
String arr2[] = s2.split(" ");
ArrayList<String> tmp1 = new ArrayList<String>();
ArrayList<String> tmp2 = new ArrayList<String>();
for (int i = 0,j=0; i < arr1.length; i++) {
if (arr1[i].equalsIgnoreCase(arr2[j])) {
tmp1.add(arr1[i]);
j++;
} else {
tmp2.add(arr1[i]);
}
}
System.err.println(tmp2);
} catch(Exception e)
{
e.printStackTrace();
}
}
}
Related
This question already has answers here:
Convert String to operator(+*/-) in java
(5 answers)
Closed 4 years ago.
How I convert String containing Mathematic arithmetic operation's like "10 + 20 - 25", I am getting String from EditText,I want to convert get the Result of operation.
Here is my code to resolve your problem:
public class ExecuteHandler {
private static Character[] OPERATORS = { '/', '*', '+', '-' };
private static final String REGEXOPERATORS = "[/+,-,/*,//,-]";
private static final String REGEXDIGITS = "(\\d+)";
private ArrayList<Character> operators = new ArrayList<>();
private ArrayList<Integer> digits = new ArrayList<>();
public String execute(String math) {
StringBuilder result = new StringBuilder();
try {
getDigits(math);
getOperators(math);
getNextOperator(operators);
for (Integer digit : digits) {
result.append(String.valueOf(digit));
}
} catch (ArithmeticException | IndexOutOfBoundsException e) {
return "ERROR";
}
return result.toString().isEmpty() ? "ERROR" : result.toString();
}
public void clear() {
operators.clear();
digits.clear();
}
private void getNextOperator(ArrayList<Character> operators) {
for (Character op : OPERATORS) {
for (int i = 0; i < operators.size(); i++) {
if (operators.get(i) == '/') {
operators.remove(i);
digits.set(i, (digits.get(i) / digits.get(i + 1)));
digits.remove(i + 1);
i -= 1;
}
}
for (int i = 0; i < operators.size(); i++) {
if (operators.get(i) == '*') {
operators.remove(i);
digits.set(i, (digits.get(i) * digits.get(i + 1)));
digits.remove(i + 1);
i -= 1;
}
}
for (int i = 0; i < operators.size(); i++) {
if (operators.get(i) == '+') {
operators.remove(i);
digits.set(i, (digits.get(i) + digits.get(i + 1)));
digits.remove(i + 1);
i -= 1;
}
}
for (int i = 0; i < operators.size(); i++) {
if (operators.get(i) == '-') {
operators.remove(i);
digits.set(i, (digits.get(i) - digits.get(i + 1)));
digits.remove(i + 1);
i -= 1;
}
}
}
}
private void getDigits(String math) {
Pattern r = Pattern.compile(REGEXDIGITS);
Matcher m = r.matcher(math);
while (m.find()) {
int t = Integer.parseInt(math.substring(m.start(), m.end()));
digits.add(t);
}
}
private void getOperators(String math) {
Pattern r = Pattern.compile(REGEXOPERATORS);
Matcher m = r.matcher(math);
while (m.find()) {
operators.add(math.charAt(m.start()));
}
}
}
Call method execute with input is string like "10 + 20 - 25:", the result will be a string of value (if success) or ERROR (if any syntax error).
How to compare app version in android
I got latest version code and current version code , but the problem is
current version is 1.0
and latest version is 1.0.0
so how to compare that float value in android
I have written a small Android library for comparing version numbers: https://github.com/G00fY2/version-compare
What it basically does is this:
public int compareVersions(String versionA, String versionB) {
String[] versionTokensA = versionA.split("\\.");
String[] versionTokensB = versionB.split("\\.");
List<Integer> versionNumbersA = new ArrayList<>();
List<Integer> versionNumbersB = new ArrayList<>();
for (String versionToken : versionTokensA) {
versionNumbersA.add(Integer.parseInt(versionToken));
}
for (String versionToken : versionTokensB) {
versionNumbersB.add(Integer.parseInt(versionToken));
}
final int versionASize = versionNumbersA.size();
final int versionBSize = versionNumbersB.size();
int maxSize = Math.max(versionASize, versionBSize);
for (int i = 0; i < maxSize; i++) {
if ((i < versionASize ? versionNumbersA.get(i) : 0) > (i < versionBSize ? versionNumbersB.get(i) : 0)) {
return 1;
} else if ((i < versionASize ? versionNumbersA.get(i) : 0) < (i < versionBSize ? versionNumbersB.get(i) : 0)) {
return -1;
}
}
return 0;
}
This snippet doesn't offer any error checks or handling. Beside that my library also supports suffixes like "1.2-rc" > "1.2-beta".
I am a bit late to the party but I have a great solution for all of you!
1. Use this class:
public class VersionComparator implements Comparator {
public boolean equals(Object o1, Object o2) {
return compare(o1, o2) == 0;
}
public int compare(Object o1, Object o2) {
String version1 = (String) o1;
String version2 = (String) o2;
VersionTokenizer tokenizer1 = new VersionTokenizer(version1);
VersionTokenizer tokenizer2 = new VersionTokenizer(version2);
int number1, number2;
String suffix1, suffix2;
while (tokenizer1.MoveNext()) {
if (!tokenizer2.MoveNext()) {
do {
number1 = tokenizer1.getNumber();
suffix1 = tokenizer1.getSuffix();
if (number1 != 0 || suffix1.length() != 0) {
// Version one is longer than number two, and non-zero
return 1;
}
}
while (tokenizer1.MoveNext());
// Version one is longer than version two, but zero
return 0;
}
number1 = tokenizer1.getNumber();
suffix1 = tokenizer1.getSuffix();
number2 = tokenizer2.getNumber();
suffix2 = tokenizer2.getSuffix();
if (number1 < number2) {
// Number one is less than number two
return -1;
}
if (number1 > number2) {
// Number one is greater than number two
return 1;
}
boolean empty1 = suffix1.length() == 0;
boolean empty2 = suffix2.length() == 0;
if (empty1 && empty2) continue; // No suffixes
if (empty1) return 1; // First suffix is empty (1.2 > 1.2b)
if (empty2) return -1; // Second suffix is empty (1.2a < 1.2)
// Lexical comparison of suffixes
int result = suffix1.compareTo(suffix2);
if (result != 0) return result;
}
if (tokenizer2.MoveNext()) {
do {
number2 = tokenizer2.getNumber();
suffix2 = tokenizer2.getSuffix();
if (number2 != 0 || suffix2.length() != 0) {
// Version one is longer than version two, and non-zero
return -1;
}
}
while (tokenizer2.MoveNext());
// Version two is longer than version one, but zero
return 0;
}
return 0;
}
// VersionTokenizer.java
public static class VersionTokenizer {
private final String _versionString;
private final int _length;
private int _position;
private int _number;
private String _suffix;
private boolean _hasValue;
VersionTokenizer(String versionString) {
if (versionString == null)
throw new IllegalArgumentException("versionString is null");
_versionString = versionString;
_length = versionString.length();
}
public int getNumber() {
return _number;
}
String getSuffix() {
return _suffix;
}
public boolean hasValue() {
return _hasValue;
}
boolean MoveNext() {
_number = 0;
_suffix = "";
_hasValue = false;
// No more characters
if (_position >= _length)
return false;
_hasValue = true;
while (_position < _length) {
char c = _versionString.charAt(_position);
if (c < '0' || c > '9') break;
_number = _number * 10 + (c - '0');
_position++;
}
int suffixStart = _position;
while (_position < _length) {
char c = _versionString.charAt(_position);
if (c == '.') break;
_position++;
}
_suffix = _versionString.substring(suffixStart, _position);
if (_position < _length) _position++;
return true;
}
}
}
2. create this function
private fun isNewVersionAvailable(currentVersion: String, latestVersion: String): Boolean {
val versionComparator = VersionComparator()
val result: Int = versionComparator.compare(currentVersion, latestVersion)
var op = "=="
if (result < 0) op = "<"
if (result > 0) op = ">"
System.out.printf("%s %s %s\n", currentVersion, op, latestVersion)
return if (op == ">" || op == "==") {
false
} else op == "<"
}
3. and just call it by
e.g. isNewVersionAvailable("1.2.8","1.2.9") where 1.2.8 is your current version here and 1.2.9 is the latest version, which returns true!
Why overcomplicate this so much?
Just scale the major, minor, patch version and you have it covered:
fun getAppVersionFromString(version: String): Int { // "2.3.5"
val versions = version.split(".") // [2, 3, 5]
val major = versions[0].toIntOrDefault(0) * 10000 // 20000
val minor = versions[1].toIntOrDefault(0) * 1000 // 3000
val patch = versions[2].toIntOrDefault(0) * 100 // 500
return major + minor + patch // 2350
}
That way when you compare e.g 9.10.10 with 10.0.0 the second one is greater.
Use the following method to compare the versions number:
Convert float to String first.
public static int versionCompare(String str1, String str2) {
String[] vals1 = str1.split("\\.");
String[] vals2 = str2.split("\\.");
int i = 0;
// set index to first non-equal ordinal or length of shortest version string
while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) {
i++;
}
// compare first non-equal ordinal number
if (i < vals1.length && i < vals2.length) {
int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i]));
return Integer.signum(diff);
}
// the strings are equal or one string is a substring of the other
// e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4"
return Integer.signum(vals1.length - vals2.length);
}
Refer the following SO question : Efficient way to compare version strings in Java
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am developing an application program which holds students names in a list and their group number.
Each student can transfer to another group so there is another field which carries their wishes.
I want the program to carry matching group number with students wishes and getting the best result with 0 conflict and updating an SQLite database.
Someone has told me to use the stable marriage algorithm: it would be perfect for this type of problem.
The problem is that I don't know much about this last one and how it would be looks like in android so if you can offer me a simple explanation and an example which has SQLite, Java code it would be perfect.
A very good explanation:
http://www.cs.berkeley.edu/~kamil/cs70/lec/lec05.html
Animation:
You can check out this animation which explains the problem nicely
http://goanimate.com/videos/0g8OutVDdMJo
This is the implementation of Gale Shapely which is a famous solution to stable marriage problem.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class GaleShapley
{
private int N, engagedCount;
private String[][] menPref;
private String[][] womenPref;
private String[] men;
private String[] women;
private String[] womenPartner;
private boolean[] menEngaged;
/** Constructor **/
public GaleShapley(String[] m, String[] w, String[][] mp, String[][] wp)
{
N = mp.length;
engagedCount = 0;
men = m;
women = w;
menPref = mp;
womenPref = wp;
menEngaged = new boolean[N];
womenPartner = new String[N];
calcMatches();
}
/** function to calculate all matches **/
private void calcMatches()
{
while (engagedCount < N)
{
int free;
for (free = 0; free < N; free++)
if (!menEngaged[free])
break;
for (int i = 0; i < N && !menEngaged[free]; i++)
{
int index = womenIndexOf(menPref[free][i]);
if (womenPartner[index] == null)
{
womenPartner[index] = men[free];
menEngaged[free] = true;
engagedCount++;
}
else
{
String currentPartner = womenPartner[index];
if (morePreference(currentPartner, men[free], index))
{
womenPartner[index] = men[free];
menEngaged[free] = true;
menEngaged[menIndexOf(currentPartner)] = false;
}
}
}
}
printCouples();
}
/** function to check if women prefers new partner over old assigned partner **/
private boolean morePreference(String curPartner, String newPartner, int index)
{
for (int i = 0; i < N; i++)
{
if (womenPref[index][i].equals(newPartner))
return true;
if (womenPref[index][i].equals(curPartner))
return false;
}
return false;
}
/** get men index **/
private int menIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (men[i].equals(str))
return i;
return -1;
}
/** get women index **/
private int womenIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (women[i].equals(str))
return i;
return -1;
}
/** print couples **/
public void printCouples()
{
System.out.println("Couples are : ");
for (int i = 0; i < N; i++)
{
System.out.println(womenPartner[i] +" "+ women[i]);
}
}
/** main function **/
public static void main(String[] args)
{
System.out.println("Gale Shapley Marriage Algorithm\n");
/** list of men **/
String[] m = {"1", "2", "3"};
/** list of women **/
String[] w = {"1", "2", "3"};
/** men preference **/
String[][] mp = null ;
/** women preference **/
String[][] wp= null ;
// Input.txt is like
// 3 <--defines the size of array
// male preference array
// 1 3 2
// 1 2 3
// 2 3 1
//female preference array
//1 3 2
//2 1 3
//2 1 3
try{
FileInputStream fstream = new FileInputStream("input.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int line=0;
int k=0;
int n=0;
int i=0;
while ((strLine = br.readLine()) != null) {
if(line==0){
n =Integer.valueOf(strLine);
mp=new String[n][n];
wp=new String[n][n];
line++;
}
else{
String[] preferences=strLine.split(" ");
if(i<n){
mp[i]=preferences;
}
else{
wp[i-n]=preferences;
}
i++;
}
}
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
GaleShapley gs = new GaleShapley(m, w, mp, wp);
}
}
I was able to execute the code below after making some changes.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class GaleShapley
{
private int N, engagedCount;
private String[][] menPref;
private String[][] womenPref;
private String[] men;
private String[] women;
private String[] womenPartner;
private boolean[] menEngaged;
public GaleShapley() {}
/** Constructor **/
public GaleShapley(String[] m, String[] w, String[][] mp, String[][] wp)
{
N = mp.length;
engagedCount = 0;
men = m;
women = w;
menPref = mp;
womenPref = wp;
menEngaged = new boolean[N];
womenPartner = new String[N];
calcMatches();
}
/** function to calculate all matches **/
private void calcMatches()
{
while (engagedCount < N)
{
int free;
for (free = 0; free < N; free++)
if (!menEngaged[free])
break;
for (int i = 0; i < N && !menEngaged[free]; i++)
{
int index = womenIndexOf(menPref[free][i]);
if (womenPartner[index] == null)
{
womenPartner[index] = men[free];
menEngaged[free] = true;
engagedCount++;
}
else
{
String currentPartner = womenPartner[index];
if (morePreference(currentPartner, men[free], index))
{
womenPartner[index] = men[free];
menEngaged[free] = true;
menEngaged[menIndexOf(currentPartner)] = false;
}
}
}
}
printCouples();
}
/** function to check if women prefers new partner over old assigned partner **/
private boolean morePreference(String curPartner, String newPartner, int index)
{
for (int i = 0; i < N; i++)
{
if (womenPref[index][i].equals(newPartner))
return true;
if (womenPref[index][i].equals(curPartner))
return false;
}
return false;
}
/** get men index **/
private int menIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (men[i].equals(str))
return i;
return -1;
}
/** get women index **/
private int womenIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (women[i].equals(str))
return i;
return -1;
}
/** print couples **/
public void printCouples()
{
System.out.println("Couples are : ");
for (int i = 0; i < N; i++)
{
System.out.println(womenPartner[i] +" "+ women[i]);
}
}
/** main function **/
public static void main(String[] args) {
System.out.println("Gale Shapley Marriage Algorithm\n");
/** list of men **/
String[] m = { "1", "2", "3" };
/** list of women **/
String[] w = { "1", "2", "3" };
/** men preference **/
String[][] mp = null;
/** women preference **/
String[][] wp = null;
try {
FileInputStream fstream = new FileInputStream("src\\input.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int line = 0;
int n = 0;
int i = 0;
while ((strLine = br.readLine()) != null) {
if (line == 0) {
n = Integer.valueOf(strLine.trim());
mp = new String[n][n];
wp = new String[n][n];
line++;
} else {
if (strLine != null && !strLine.equals("") && !strLine.contains("male")
&& !strLine.contains("female")) {
String[] preferences = strLine.split(" ");
if (i < n) {
mp[i] = preferences;
} else {
if (i - n < w.length) {
wp[i - n] = preferences;
}
}
i++;
}
}
}
in.close();
new GaleShapley(m, w, mp, wp);
} catch (Exception e) {// Catch exception if any
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
}
The result is:
Gale Shapley Marriage Algorithm
Couples are :
1 1
2 2
3 3
I need to fill a vector with integers, but I have some troubles, I need to fill it with random numbers, but not two numbers in a row. (ex. not like this: 1,4,4,3,5,9)
I made this code but it does not work well :
# first time loja=1;
but until the game : loja++;
int[] con;
Random Method :
private int nasiqim (int max){
Random nasiqimi = new Random();
int i = 0;
i=nasiqimi.nextInt(max);
return i;
}
Working Code :
int i;
con = new int [loja];
for (i=0; i<loja; i++)
{
con[i] = nasiqim(8);
if(i>0){
while(con[i]==con[i-1])
{
con[i] =nasiqim(8);
}
}
i++;
}
The results are like this:
1
1,4
1,4,1
1,4,1,4
1,4,1,4,1
5,3,5,3,5,3
5,3,5,3,5,3,5
And this is not what I need, I need the numbers to really random, not like this,
Will be great if list will be like this something : 1,5,6,7,3,0,2,4,1,0,2,3...
Thank you!!
private int[] con = null;
private final Random nasiqimi = new Random();
/**
* Test run random.
*/
#Test
public void testRunRandom() {
int loja = 10;
con = new int[loja];
for (int i = 0; i < loja; i++) {
int nextRandom = 0;
while (true) {
nextRandom = nasiqim(8);
if (i == 0 || con[i - 1] != nextRandom) {
con[i] = nextRandom;
break;
}
}
}
}
/**
* Gets the random.
*
* #param max the max
* #return the random
*/
private int nasiqim(int max) {
return nasiqimi.nextInt(max);
}
I've created a sample class
import java.util.*;
public class Foo {
static Random r = new Random();
static int[] con;
static int loja = 8;
private static int randomInt(int max) {
return r.nextInt(max);
}
public static void main(String args[]) {
int i;
con = new int[loja];
for (i = 0; i < loja; i++) {
con[i] = randomInt(8);
if (i > 0) {
while (con[i] == con[i - 1]) {
con[i] = randomInt(8);
}
}
}
System.out.println( Arrays.toString(con));
}
}
All variables are static, notice I get rid of the i++; increment at the end of the for loop.
i have string like these for example
309\306\308\337_338
309\306\337_338
310
311\315_316\336_337
311\315_316\336_337
311\335_336
these strings means list of page number , for example string "309\306\308\337_339" means
pages 309,306,308,337,338,339
i want to pass one of these string to function which return it as string like this
309,306,308,337,338,339
this function do that but in c# , i want to impalement in android
private static string Get_PageNumbers(string str)
{
ArrayList arrAll = new ArrayList();
MatchCollection match;
string[] excar;
string strid, firstNumber, lastlNumber;
int fn, ln;
ArrayList arrID = new ArrayList();
//***In Case The Range Number Between "_"
if (str.Contains("_"))
{
// match_reg = new Regex("(w?[\\d]+)*(_[\\d]+)");
Regex matchReg = new Regex("(w?[\\69]+_[\\d]+)*(q?[\\d]+//)*(a?[\\d]+_[\\d]+)*(y?[\\d]+)*");
match = matchReg.Matches(str);
int count = match.Count;
excar = new string[0];
for (int i = 0; i < count; i++)
{
Array.Resize(ref excar, count);
excar[i] = match[i].Groups[0].Value;
if (excar[i] != string.Empty)
arrID.Add(excar[i]);
}
//******IF Array Contains Range Of Number Like"102_110"
if (str.Contains("_"))
{
for (int i = 0; i < arrID.Count; i++)
{
strid = arrID[i].ToString();
if (arrID[i].ToString().Contains("_"))
{
int idy = strid.LastIndexOf("_");
firstNumber = strid.Substring(0, idy);
if (idy != -1)
{
lastlNumber = strid.Substring(idy + 1);
fn = int.Parse(firstNumber);
arrAll.Add(fn);
ln = int.Parse(lastlNumber);
for (int c = fn; c < ln; c++)
{
fn++;
arrAll.Add(fn);
}
}
}
else
{
arrAll.Add(arrID[i].ToString());
}
}
//******If Array Contain More Than One Number
if (arrAll.Count > 0)
{
str = "";
for (int i = 0; i < arrAll.Count; i++)
{
if (str != string.Empty)
str = str + "," + arrAll[i];
else
str = arrAll[i].ToString();
}
}
}
}
//***If string Contains between "/" only without "_"
else if (str.Contains("/") && !str.Contains("_"))
{
str = str.Replace("/", ",");
}
else if (str.Contains("\\"))
{
str = str.Replace("\\", ",");
}
return str;
}
I think this is easier to do with split function:
public static String Get_PageNumbers(String str) {// Assume str = "309\\306\\308\\337_338"
String result = "";
String[] pages = str.split("\\\\"); // now we have pages = {"309","306","308","337_338"}
for (int i = 0; i < pages.length; i++) {
String page = pages[i];
int index = page.indexOf('_');
if (index != -1) { // special case i.e. "337_338", index = 3
int start = Integer.parseInt(page.substring(0, index)); // start = 337
int end = Integer.parseInt(page.substring(index + 1)); // end = 338
for (int j = start; j <= end; j++) {
result += String.valueOf(j);
if (j != end) { // don't add ',' after last one
result += ",";
}
}
} else { // regular case i.e. "309","306","308"
result += page;
}
if (i != (pages.length-1)) { // don't add ',' after last one
result += ",";
}
}
return result; // result = "309,306,308,337,338"
}
For example this function when called as follows:
String result1 = Get_PageNumbers("309\\306\\308\\337_338");
String result2 = Get_PageNumbers("311\\315_316\\336_337");
String result3 = Get_PageNumbers("310");
Returns:
309,306,308,337,338
311,315,316,336,337
310
if i can suggest different implementation....
first, split string with "\" str.split("\\");, here you receive an array string with single number or a pattern like "num_num"
for all string founded, if string NOT contains "" char, put string in another array (othArr named), than, you split again with "" str.split("_");, now you have a 2 position array
convert that 2 strings in integer
now create a loot to min val form max val or two strings converted (and put it into othArr)
tranform othArr in a string separated with ","