Android, Random do not repeat same number twice in a row - android

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.

Related

Calculating combination in Android Studio

I have a javascript to calculate combination and works great. But when I tried to work on Android studio code it gets wrong result.
Js
var n=16;
var r=2;
function faktor(sayi) {
var sonuc=1;
for(var i=1;i<=sayi;i++)
{
sonuc*=i;
}
return sonuc;
}
function calculate (){
var sonuc2=faktor(n)/(faktor(r)*faktor(n-r));
console.log(sonuc2);
}
calculate();
Console log = 120
That's how I used in Android Studio
public static int tiklanan = 16;
public static int kombinasyon = 2;
int sonuc2;
private int faktor(int sayi){
int sonuc=1;
for(int i=1;i<=sayi;i++)
{
sonuc*=i;
}
return sonuc;
}
private void posibilityhesapla(){
sonuc2=faktor(tiklanan)/(faktor(kombinasyon)*faktor(tiklanan-kombinasyon));
Toast.makeText(this, "/"+sonuc2, Toast.LENGTH_SHORT).show();
}
sonuc2 always returns -1 but it must 120.
What I'm missing here ?
#Dorbagna your Integer variable has overflowed the value. Converting sonuc from int to long will fix your issue.
faktor(tiklanan) = faktor(16) = 20922789888000
While maximum value int can hold is 2147483647 (Integer.MAX_VALUE)
public static int tiklanan = 16;
public static int kombinasyon = 2;
// Change variable int type to long
long sonuc2;
//change return type to long
private long faktor(int sayi) {
// Change local variable int type to long
long sonuc = 1;
for (int i = 1; i <= sayi; i++) {
sonuc *= i;
}
return sonuc;
}
private void posibilityhesapla() {
sonuc2 = faktor(tiklanan) / (faktor(kombinasyon) * faktor(tiklanan - kombinasyon));
Toast.makeText(this, "/" + sonuc2, Toast.LENGTH_SHORT).show();
}

Justify text inside Android Textview

I want to Justify text inside Android TextView. With copy and share function and can accept spannable string. Can someone help me. It's so important for me. Thank you in advance
I have a solution for the text-justify in Android.
I have created a Custom Textview class, with this you can solve the justification issue in Android.
<com.trailcreator.util.JustifyCustomTextView
android:id="#+id/yourTextViewID"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Here is the class
public class JustifyCustomTextView extends android.support.v7.widget.AppCompatTextView {
//Object that helps us to measure the words and characters like spaces.
private Paint mPaint;
//Thin space (Hair Space actually) character that will fill the spaces
private String mThinSpace = "\u200A";
//String that will storage the text with the inserted spaces
private String mJustifiedText = "";
//Float that represents the actual width of a sentence
private float mSentenceWidth = 0;
//Integer that counts the spaces needed to fill the line being processed
private int mWhiteSpacesNeeded = 0;
//Integer that counts the actual amount of words in the sentence
private int mWordsInThisSentence = 0;
//ArrayList of Strings that will contain the words of the sentence being processed
private ArrayList<String> mTemporalLine = new ArrayList<String>();
//StringBuilder that will hold the temporal chunk of the string to calculate word index.
private StringBuilder mStringBuilderCSequence = new StringBuilder();
//List of SpanHolder class that will hold the spans within the giving string.
private List<SpanHolder> mSpanHolderList = new ArrayList<>();
//StringBuilder that will store temp data for joining sentence.
private StringBuilder sentence = new StringBuilder();
private int mViewWidth;
private float mThinSpaceWidth;
private float mWhiteSpaceWidth;
//Default Constructors!
public JustifyCustomTextView(Context context) {
super(context);
}
public JustifyCustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public JustifyCustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (mJustifiedText.replace(" ", "")
.replace("", mThinSpace)
.equals(this.getText().toString().replace(" ", "").replace("", mThinSpace))) {
return;
}
ViewGroup.LayoutParams params = this.getLayoutParams();
CharSequence charSequence = this.getText();
mSpanHolderList.clear();
String[] words = this.getText().toString().split(" ");
//Get spans within the string and adds the instance references into the
//SpanHolderList to be applied once the justify process has been performed.
SpannableString s = SpannableString.valueOf(charSequence);
if ((charSequence instanceof SpannedString)) {
for (int i = 0; i < this.getText().length() - 1; i++) {
CharacterStyle[] spans =
((SpannedString) charSequence).getSpans(i, i + 1, CharacterStyle.class);
if (spans != null && spans.length > 0) {
for (CharacterStyle span : spans) {
int spaces =
charSequence.toString().substring(0, i).split(" ").length + charSequence.toString()
.substring(0, i)
.split(mThinSpace).length;
SpanHolder spanHolder =
SpanHolder.getNewInstance(spans, s.getSpanStart(span), s.getSpanEnd(span), spaces);
mStringBuilderCSequence.setLength(0);
for (int j = 0; j <= words.length - 1; j++) {
mStringBuilderCSequence.append(words[j]);
mStringBuilderCSequence.append(" ");
if (mStringBuilderCSequence.length() > i) {
if (words[j].trim().replace(mThinSpace, "").length() == 1) {
spanHolder.setWordHolderIndex(j);
} else {
spanHolder.setWordHolderIndex(j);
spanHolder.setTextChunkPadded(true);
}
break;
}
}
mSpanHolderList.add(spanHolder);
}
}
}
}
mPaint = this.getPaint();
mViewWidth = this.getMeasuredWidth() - (getPaddingLeft() + getPaddingRight());
//This class won't justify the text if the TextView has wrap_content as width
//And won't repeat the process of justify text if it's already done.
//AND! won't justify the text if the view width is 0
if (params.width != ViewGroup.LayoutParams.WRAP_CONTENT
&& mViewWidth > 0
&& words.length > 0
&& mJustifiedText.isEmpty()) {
mThinSpaceWidth = mPaint.measureText(mThinSpace);
mWhiteSpaceWidth = mPaint.measureText(" ");
for (int i = 0; i <= words.length - 1; i++) {
boolean containsNewLine = (words[i].contains("\n") || words[i].contains("\r"));
if (containsNewLine) {
String[] splitted = words[i].split("(?<=\\n)");
for (String splitWord : splitted) {
processWord(splitWord, splitWord.contains("\n"));
}
} else {
processWord(words[i], false);
}
}
mJustifiedText += joinWords(mTemporalLine);
}
//Apply the extra spaces to the items of the SpanList that were added due
//the justifying process.
SpannableString spannableString = SpannableString.valueOf(mJustifiedText);
for (SpanHolder sH : mSpanHolderList) {
int spaceCount = 0, wordCount = 0;
boolean isCountingWord = false;
int j = 0;
while (wordCount < (sH.getWordHolderIndex() + 1)) {
if (mJustifiedText.charAt(j) == ' ' || mJustifiedText.charAt(j) == ' ') {
spaceCount++;
if (isCountingWord) {
wordCount++;
}
isCountingWord = false;
} else {
isCountingWord = true;
}
j++;
}
sH.setStart(
sH.getStart() + spaceCount - sH.getCurrentSpaces() + (sH.isTextChunkPadded() ? 1 : 0));
sH.setEnd(
sH.getEnd() + spaceCount - sH.getCurrentSpaces() + (sH.isTextChunkPadded() ? 1 : 0));
}
//Applies spans on Justified String.
for (SpanHolder sH : mSpanHolderList) {
for (CharacterStyle cS : sH.getSpans())
spannableString.setSpan(cS, sH.getStart(), sH.getEnd(), 0);
}
if (!mJustifiedText.isEmpty()) this.setText(spannableString);
}
private void processWord(String word, boolean containsNewLine) {
if ((mSentenceWidth + mPaint.measureText(word)) < mViewWidth) {
mTemporalLine.add(word);
mWordsInThisSentence++;
mTemporalLine.add(containsNewLine ? "" : " ");
mSentenceWidth += mPaint.measureText(word) + mWhiteSpaceWidth;
if (containsNewLine) {
mJustifiedText += joinWords(mTemporalLine);
resetLineValues();
}
} else {
while (mSentenceWidth < mViewWidth) {
mSentenceWidth += mThinSpaceWidth;
if (mSentenceWidth < mViewWidth) mWhiteSpacesNeeded++;
}
if (mWordsInThisSentence > 1) {
insertWhiteSpaces(mWhiteSpacesNeeded, mWordsInThisSentence, mTemporalLine);
}
mJustifiedText += joinWords(mTemporalLine);
resetLineValues();
if (containsNewLine) {
mJustifiedText += word;
mWordsInThisSentence = 0;
return;
}
mTemporalLine.add(word);
mWordsInThisSentence = 1;
mTemporalLine.add(" ");
mSentenceWidth += mPaint.measureText(word) + mWhiteSpaceWidth;
}
}
//Method that resets the values of the actual line being processed
private void resetLineValues() {
mTemporalLine.clear();
mSentenceWidth = 0;
mWhiteSpacesNeeded = 0;
mWordsInThisSentence = 0;
}
//Function that joins the words of the ArrayList
private String joinWords(ArrayList<String> words) {
sentence.setLength(0);
for (String word : words) {
sentence.append(word);
}
return sentence.toString();
}
//Method that inserts spaces into the words to make them fix perfectly in the width of the view. I know I'm a genius naming stuff :)
private void insertWhiteSpaces(int whiteSpacesNeeded, int wordsInThisSentence,
ArrayList<String> sentence) {
if (whiteSpacesNeeded == 0) return;
if (whiteSpacesNeeded == wordsInThisSentence) {
for (int i = 1; i < sentence.size(); i += 2) {
sentence.set(i, sentence.get(i) + mThinSpace);
}
} else if (whiteSpacesNeeded < wordsInThisSentence) {
for (int i = 0; i < whiteSpacesNeeded; i++) {
int randomPosition = getRandomEvenNumber(sentence.size() - 1);
sentence.set(randomPosition, sentence.get(randomPosition) + mThinSpace);
}
} else if (whiteSpacesNeeded > wordsInThisSentence) {
//I was using recursion to achieve this... but when you tried to watch the preview,
//Android Studio couldn't show any preview because a StackOverflow happened.
//So... it ended like this, with a wild while xD.
while (whiteSpacesNeeded > wordsInThisSentence) {
for (int i = 1; i < sentence.size() - 1; i += 2) {
sentence.set(i, sentence.get(i) + mThinSpace);
}
whiteSpacesNeeded -= (wordsInThisSentence - 1);
}
if (whiteSpacesNeeded == 0) return;
if (whiteSpacesNeeded == wordsInThisSentence) {
for (int i = 1; i < sentence.size(); i += 2) {
sentence.set(i, sentence.get(i) + mThinSpace);
}
} else if (whiteSpacesNeeded < wordsInThisSentence) {
for (int i = 0; i < whiteSpacesNeeded; i++) {
int randomPosition = getRandomEvenNumber(sentence.size() - 1);
sentence.set(randomPosition, sentence.get(randomPosition) + mThinSpace);
}
}
}
}
//Gets a random number, it's part of the algorithm... don't blame me.
private int getRandomEvenNumber(int max) {
Random rand = new Random();
// nextInt is normally exclusive of the top value,
return rand.nextInt((max)) & ~1;
}
}
public class SpanHolder {
private CharacterStyle[] spans;
private int start;
private int end;
private boolean textChunkPadded =false;
private int wordHolderIndex;
private int currentSpaces;
public SpanHolder(CharacterStyle[] spans, int start, int end, int spaces){
this.setSpans(spans);
this.setStart(start);
this.setEnd(end);
this.setCurrentSpaces(spaces);
}
public static SpanHolder getNewInstance(CharacterStyle[] spans, int start, int end, int spaces){
return new SpanHolder(spans,start,end,spaces);
}
public boolean isTextChunkPadded() {
return textChunkPadded;
}
public void setTextChunkPadded(boolean textChunkPadded) {
this.textChunkPadded = textChunkPadded;
}
public int getWordHolderIndex() {
return wordHolderIndex;
}
public void setWordHolderIndex(int wordHolderIndex) {
this.wordHolderIndex = wordHolderIndex;
}
public CharacterStyle[] getSpans() {
return spans;
}
public void setSpans(CharacterStyle[] spans) {
this.spans = spans;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public int getCurrentSpaces() {
return currentSpaces;
}
public void setCurrentSpaces(int currentSpaces) {
this.currentSpaces = currentSpaces;
}
}
GOOD LUCK! (Y)

Dynamic playlists with Exoplayer 2

I'd like to use ExoPlayer2 with playlists having possibility to dinamically change the tracks (add or remove them from playlist) and change the loop settings.
Since ConcatenatingMediaSource has static arrays (and not lists), I'm implementing a DynamicMediaSource, like Concatenating one but with lists instead of arrays and one mode method addSource to add one more media source to the list.
public void addSource(MediaSource mediaSource) {
this.mediaSources.add(mediaSource);
duplicateFlags = buildDuplicateFlags(this.mediaSources);
if(!mediaSources.isEmpty())
prepareSource(mediaSources.size() -1);
else
prepareSource(0);
}
When I invoke addSource
MediaSource ms = buildMediaSource(mynewuri, null);
mediaSource.addSource(ms);
the track is added to the arrays but it seems something is missing because I always obtain ArrayOutOfBoundsException in createPeriod method.
In createPeriod the method
mediaSources.get(sourceIndex)...
is trying to access the index = mediaSources.size().
Can you help me?
I eventually managed it.
It was my fault during the conversion from arrays to lists.
I had to use SparseArrays for timelines and manifests and everything began to work.
In the DynamicMediaSource simply set the following types:
private final List<MediaSource> mediaSources;
private final SparseArray<Timeline> timelines;
private final SparseArray<Object> manifests;
private final Map<MediaPeriod, Integer> sourceIndexByMediaPeriod;
private SparseArray<Boolean> duplicateFlags;
you have to use sparse arrays to set the proper values into the timelines and manifests in the method
private void handleSourceInfoRefreshed(int sourceFirstIndex, Timeline sourceTimeline,
Object sourceManifest) {
// Set the timeline and manifest.
timelines.put(sourceFirstIndex, sourceTimeline);
manifests.put(sourceFirstIndex, sourceManifest);
// Also set the timeline and manifest for any duplicate entries of the same source.
for (int i = sourceFirstIndex + 1; i < mediaSources.size(); i++) {
if (mediaSources.get(i).equals(mediaSources.get(sourceFirstIndex))) {
timelines.put(i, sourceTimeline);
manifests.put(i, sourceManifest);
}
}
for(int i= 0; i<mediaSources.size(); i++){
if(timelines.get(i) == null){
// Don't invoke the listener until all sources have timelines.
return;
}
}
timeline = new DynamicTimeline(new ArrayList(asList(timelines)));
listener.onSourceInfoRefreshed(timeline, new ArrayList(asList(manifests)));
}
Here is the complete code of DynamicMediaSource class:
public final class DynamicMediaSource implements MediaSource {
private static final String TAG = "DynamicSource";
private final List<MediaSource> mediaSources;
private final List<Timeline> timelines;
private final List<Object> manifests;
private final Map<MediaPeriod, Integer> sourceIndexByMediaPeriod;
private SparseArray<Boolean> duplicateFlags;
private Listener listener;
private DynamicTimeline timeline;
/**
* #param mediaSources The {#link MediaSource}s to concatenate. It is valid for the same
* {#link MediaSource} instance to be present more than once in the array.
*/
public DynamicMediaSource(MediaSource... mediaSources) {
this.mediaSources = new ArrayList<MediaSource>(Arrays.asList(mediaSources));
timelines = new ArrayList<Timeline>();
manifests = new ArrayList<Object>();
sourceIndexByMediaPeriod = new HashMap<>();
duplicateFlags = buildDuplicateFlags(this.mediaSources);
}
public void addSource(MediaSource mediaSource) {
this.mediaSources.add(mediaSource);
duplicateFlags = buildDuplicateFlags(this.mediaSources);
/*if(!mediaSources.isEmpty())
prepareSource(mediaSources.size() -1);
else
prepareSource(0);*/
}
#Override
public void prepareSource(Listener listener) {
this.listener = listener;
for (int i = 0; i < mediaSources.size(); i++) {
prepareSource(i);
/*if (duplicateFlags.get(i) == null || !duplicateFlags.get(i)) {
final int index = i;
mediaSources.get(i).prepareSource(new Listener() {
#Override
public void onSourceInfoRefreshed(Timeline timeline, Object manifest) {
handleSourceInfoRefreshed(index, timeline, manifest);
}
});
}*/
}
}
private void prepareSource(int sourceindex) {
if (duplicateFlags.get(sourceindex) == null || !duplicateFlags.get(sourceindex)) {
final int index = sourceindex;
mediaSources.get(sourceindex).prepareSource(new Listener() {
#Override
public void onSourceInfoRefreshed(Timeline timeline, Object manifest) {
handleSourceInfoRefreshed(index, timeline, manifest);
}
});
}
}
#Override
public void maybeThrowSourceInfoRefreshError() throws IOException {
for (int i = 0; i < mediaSources.size(); i++) {
if (duplicateFlags.get(i) == null || !duplicateFlags.get(i)) {
mediaSources.get(i).maybeThrowSourceInfoRefreshError();
}
}
}
#Override
public MediaPeriod createPeriod(int index, Callback callback, Allocator allocator,
long positionUs) {
int sourceIndex = timeline.getSourceIndexForPeriod(index);
int periodIndexInSource = index - timeline.getFirstPeriodIndexInSource(sourceIndex);
MediaPeriod mediaPeriod = mediaSources.get(sourceIndex).createPeriod(periodIndexInSource, callback,
allocator, positionUs);
sourceIndexByMediaPeriod.put(mediaPeriod, sourceIndex);
return mediaPeriod;
}
#Override
public void releasePeriod(MediaPeriod mediaPeriod) {
int sourceIndex = sourceIndexByMediaPeriod.get(mediaPeriod);
sourceIndexByMediaPeriod.remove(mediaPeriod);
mediaSources.get(sourceIndex).releasePeriod(mediaPeriod);
}
#Override
public void releaseSource() {
for (int i = 0; i < mediaSources.size(); i++) {
if (duplicateFlags.get(i) == null || !duplicateFlags.get(i)) {
mediaSources.get(i).releaseSource();
}
}
}
private void handleSourceInfoRefreshed(int sourceFirstIndex, Timeline sourceTimeline,
Object sourceManifest) {
// Set the timeline and manifest.
timelines.add(sourceFirstIndex, sourceTimeline);
manifests.add(sourceFirstIndex, sourceManifest);
// Also set the timeline and manifest for any duplicate entries of the same source.
for (int i = sourceFirstIndex + 1; i < mediaSources.size(); i++) {
if (mediaSources.get(i).equals(mediaSources.get(sourceFirstIndex))) {
timelines.add(i, sourceTimeline);
manifests.add(i, sourceManifest);
}
}
for (Timeline timeline : timelines) {
if (timeline == null) {
// Don't invoke the listener until all sources have timelines.
return;
}
}
timeline = new DynamicTimeline(new ArrayList(timelines));
listener.onSourceInfoRefreshed(timeline, new ArrayList(manifests));
}
private static SparseArray<Boolean> buildDuplicateFlags(List<MediaSource> mediaSources) {
SparseArray<Boolean> duplicateFlags = new SparseArray<Boolean>();
IdentityHashMap<MediaSource, Void> sources = new IdentityHashMap<>(mediaSources.size());
for (int i = 0; i < mediaSources.size(); i++) {
MediaSource mediaSource = mediaSources.get(i);
if (!sources.containsKey(mediaSource)) {
sources.put(mediaSource, null);
} else {
duplicateFlags.setValueAt(i, true);
}
}
return duplicateFlags;
}
/**
* A {#link Timeline} that is the concatenation of one or more {#link Timeline}s.
*/
private static final class DynamicTimeline extends Timeline {
private final List<Timeline> timelines;
private final List<Integer> sourcePeriodOffsets;
private final List<Integer> sourceWindowOffsets;
public DynamicTimeline(List<Timeline> timelines) {
List<Integer> sourcePeriodOffsets = new ArrayList<>();
List<Integer> sourceWindowOffsets = new ArrayList<>();
int periodCount = 0;
int windowCount = 0;
for (Timeline timeline : timelines) {
periodCount += timeline.getPeriodCount();
windowCount += timeline.getWindowCount();
sourcePeriodOffsets.add(periodCount);
sourceWindowOffsets.add(windowCount);
}
this.timelines = timelines;
this.sourcePeriodOffsets = sourcePeriodOffsets;
this.sourceWindowOffsets = sourceWindowOffsets;
}
#Override
public int getWindowCount() {
return sourceWindowOffsets.get(sourceWindowOffsets.size() - 1);
}
#Override
public Window getWindow(int windowIndex, Window window, boolean setIds) {
int sourceIndex = getSourceIndexForWindow(windowIndex);
int firstWindowIndexInSource = getFirstWindowIndexInSource(sourceIndex);
int firstPeriodIndexInSource = getFirstPeriodIndexInSource(sourceIndex);
timelines.get(sourceIndex).getWindow(windowIndex - firstWindowIndexInSource, window, setIds);
window.firstPeriodIndex += firstPeriodIndexInSource;
window.lastPeriodIndex += firstPeriodIndexInSource;
return window;
}
#Override
public int getPeriodCount() {
return sourcePeriodOffsets.get(sourcePeriodOffsets.size() - 1);
}
#Override
public Period getPeriod(int periodIndex, Period period, boolean setIds) {
int sourceIndex = getSourceIndexForPeriod(periodIndex);
int firstWindowIndexInSource = getFirstWindowIndexInSource(sourceIndex);
int firstPeriodIndexInSource = getFirstPeriodIndexInSource(sourceIndex);
timelines.get(sourceIndex).getPeriod(periodIndex - firstPeriodIndexInSource, period, setIds);
period.windowIndex += firstWindowIndexInSource;
if (setIds) {
period.uid = Pair.create(sourceIndex, period.uid);
}
return period;
}
#Override
public int getIndexOfPeriod(Object uid) {
if (!(uid instanceof Pair)) {
return C.INDEX_UNSET;
}
Pair<?, ?> sourceIndexAndPeriodId = (Pair<?, ?>) uid;
if (!(sourceIndexAndPeriodId.first instanceof Integer)) {
return C.INDEX_UNSET;
}
int sourceIndex = (Integer) sourceIndexAndPeriodId.first;
Object periodId = sourceIndexAndPeriodId.second;
if (sourceIndex < 0 || sourceIndex >= timelines.size()) {
return C.INDEX_UNSET;
}
int periodIndexInSource = timelines.get(sourceIndex).getIndexOfPeriod(periodId);
return periodIndexInSource == C.INDEX_UNSET ? C.INDEX_UNSET
: getFirstPeriodIndexInSource(sourceIndex) + periodIndexInSource;
}
private int getSourceIndexForPeriod(int periodIndex) {
return Util.binarySearchFloor(sourcePeriodOffsets, periodIndex, true, false) + 1;
}
private int getFirstPeriodIndexInSource(int sourceIndex) {
return sourceIndex == 0 ? 0 : sourcePeriodOffsets.get(sourceIndex - 1);
}
private int getSourceIndexForWindow(int windowIndex) {
return Util.binarySearchFloor(sourceWindowOffsets, windowIndex, true, false) + 1;
}
private int getFirstWindowIndexInSource(int sourceIndex) {
return sourceIndex == 0 ? 0 : sourceWindowOffsets.get(sourceIndex - 1);
}
}
}

Stable Marriage algorithm for student×group association [closed]

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

use eratosthenes sieve to find prime

hello i want my app find prime between two number with sieve algorithm i am use this code but its not working well what can i do for improve this code to my goal please help me
public int[] GetPrimes() {
int[] primesData = new int[maxValue+1];
int[] results = new int[maxValue];
int i;
int result_count = 0;
for (i=MIN_VALUE; i<=maxValue; i++) {
primesData[i] = PRIME_UNKNOWN;
}
for (i=MIN_VALUE; i<=maxValue; i++) {
if (primesData[i] == PRIME_UNKNOWN) {
primesData[i] = PRIME_YES;
results[result_count++] = i;
int j;
for (j=i; j<=maxValue; j = j + i) {
primesData[j] = PRIME_NO;
}
}
}
int[] retval = new int[result_count];
for (i=0; i<result_count; i++) {
retval[i] = results[i];
}
tvresult.setText(retval.toString());
return retval;
}
}
The algorithm is correct. Likely you are launching it with wrong values as input.
Ensure to have MIN_VALUE set to value 2 and prepopulate retval with 1 i.e.:
int[] retval = new int[result_count+1];
retval[0] = 1;
for (i=0; i<result_count; i++) {
retval[i+1] = results[i];
For the printing issue:
tvresult.setText(Arrays.toString(retval));
Because retval.toString() just returns the object reference not the content. This is true for any Java array. Instead use Arrays.toString().

Categories

Resources