It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'd like to create a matrix like this one:
It's the transform of a graph in a matrix where a, b, c and so on are the vertices and the values represent 0 if the vertices are disconnected and 1 if they're connected.
I take two vertices randomply (i.e. c and d) and I'd like to access the value of those vertices in the matrix as M[c][d] and, also, M[d][c].
How can I do this?
If you will use integer indexes instead of letters you will be able to say m[2][3], if the matrix is defined as: int[][] m;
If you need to access the values using string coordinates, probably you should take a look at the Table class from Guava, see: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Table.html.
This way, you will be able to declare your matrix like: Table<String,String,String> and insert values using: put(String rowKey, String columnKey, String value) method and access them using get(String rowKey, String columnKey)
If you trylly want to use letters (chars) as indexes then you'll have to take an alternative approach. You can create your own structure that takes char as an index. Since a two dimensional array can be seen as an array of arrays, you can use a Map or Map objects.
You won't be able to access the objects the way you expect with this, instead you'll have to invoke map.get('c').get('d').
Another approach is to create a sort of "rosetta stone" that translates your char into the corresponding index. This is particulary useful for small graphs, since big ones generate inmense matrices and getting the index there depends on how will you address them. For example:
public class IndexInterpreter {
//Using a switch here to illustrate, you can make your own mapping logic.
public static int getIndex(char letter) {
switch(letter) {
case 'a':
return 0;
case 'b':
return 1;
//the swtich goes on and on...
}
}
}
and then, while calling the matrix you just translate the letters into their corresponding indexes:
int i1 = IndexInterpreter.getIndex('c');
int i2 = IndexInterpreter.getIndex('d');
m[i1][i2]
or, if you like
m[IndexInterpreter.getIndex('c')][IndexInterpreter.getIndex('d')]
matrix would be a 2D array
String[][] matrix = new String[6][7]
you could then populate it using
matrix[1][1] = "1";
To get the cell you want you wuld do
String val = mattix[3][5];
This link may help
Related
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 6 years ago.
Improve this question
Actually, this question was asked one of the interviews, I do not know the exact answer, could you explain in detail ?
How would you select 100 random lines from a file with a 1 million
lines? Can`t read file into memory.
Typically, in such scenarios, you do not know the number of items in the input file in advance (and you want to avoid requiring two passes over your data, to check the number of available items first). In that case the solution proposed by #radoh and others, where you will create indices to select from, will not work.
In such cases, you can use reservoir sampling: You only need to know the number of items you want to select (k as follows) and you iterate over the input data (S[1..n]). Below is the pseudocode taken from Wikipedia, I'll leave it to your practice to convert this into a working Java method (the method would typically look something like List<X> sample(Stream<X> data, int k)):
/*
S has items to sample, R will contain the result
*/
ReservoirSample(S[1..n], R[1..k])
// fill the reservoir array
for i = 1 to k
R[i] := S[i]
// replace elements with gradually decreasing probability
for i = k+1 to n
j := random(1, i) // important: inclusive range
if j <= k
R[j] := S[i]
Note that although the code mentions n explicitly (i.e. the number of input items), you do not need to know that value prior to computation. You can simply iterate over an Iterator or Stream (representing lines from a file in your case) and only need to keep the result array or collection R in memory. You can even sample a continuous stream, and at each point in time (at least, as soon, as you've seen k samples) you have k randomly chosen items.
Generate the 100 random (unique) numbers (ranging from 0..1000000-1) into a list and then go through the file reading the lines with indexes from the list. Ideally, the list of numbers should be a Set.
Pseudocode:
int i = 0;
List<String> myLines = new ArrayList();
while (fileScanner.hasNext()) {
String line = fileScanner.nextLine();
if (myRandomNumbers.contains(i)) {
myLines.add(line);
}
i++;
}
Here's a pretty efficient way to do it:
Iterator<String> linesIter = ...
List<String> selectedLines = new ArrayList();
Random rng = new Random(seed);
int linesStillNeeded = 100;
int linesRemaining = 1000000;
while (linesStillNeeded > 0) {
String line = linesIter.next();
linesRemaining--;
if (rng.nextInt(linesRemaining) < linesStillNeeded) {
selectedLines.add(line);
linesStillNeeded--;
}
}
I haven't coded in Java in a while, so you might want to treat this as pseudo-code.
This algorithm is based on the fact that the probability that any given line (assuming we are uniformly selecting k distinct lines out of a total of n lines) will be contained in the collection with probability k/n. This follows from
1) the number collections of k distinct lines (out of n lines) is choose(n, k),
2) the number of collections of k distinct lines (out of n lines) which contain a particular line is choose(n-1, k-1), and
3) choose(n-1,k-1)/choose(n,k) = k/n
Note that k and n here correspond to linesStillNeeded and linesStillRemaining in the code respectively.
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 8 years ago.
Improve this question
I have two large data sets of numeric keys (millions of entries in each) and need to set up a data structure where I can quickly identify key matches between the two sets, allowing for some fixed variation.
So for instance, if there's a value of 356 in one set, I'd like to find any instances of 355, 356 or 357 in the other set. My initial idea was to set up two HashMaps, iterate over the one with the least amount of keys, and then query the larger one over the range (so querying for 355, 356, or 357 in the larger map).
Is there a particular data structure/matching algorithm for numeric values that I should be looking into?
Maybe a java BitSet could be useful in that case. Here's a code sample that uses BitSet of size = 1000000 with a range = 5 to do the check around each values from the first set into the second :
import java.util.*;
import java.lang.*;
import java.io.*;
class CheckRange
{
public static void main (String[] args) throws java.lang.Exception
{
int range = 5;
int maxSize = 1000000;
// Prepare the main BitSet (bs)
BitSet bs = new BitSet(maxSize);
bs.set(357);
bs.set(599001);
bs.set(123456);
// ...
// Prepare the BitSet to check in
BitSet bs2 = new BitSet(maxSize);
bs2.set(5688);
bs2.set(566685);
bs2.set(988562);
// ...
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
// Compute the ranges, checking the boundaries
int minIndex = Math.max(i - range, 0);
int maxIndex = Math.min(i + range, maxSize);
// Extract the matching subset
BitSet subset = bs2.get(minIndex, maxIndex);
// Print the number of bits set
System.out.println("Number of bit set int bs2 from bs at index " + i + " is " + subset.cardinality());
}
}
}
I'd suggest you start with the Java Set. The "matches between the two sets" that you are seeking sounds a lot like a set intersection.
See API for set operations in Java? and take a look at the description of retainAll.
I will try to summarize a little bit.
Option one - sorted arrays. With binary search, you will be able to find exact value with O(log N) complexity (here and below N is a number of elements in the structure). So, for your operation - log n (search in the first set) + log n (search in the second) + constant (check what you called variation), which is 2 * log N + constant which is O(log N). If data in the collections is changing, you'll have to spend O(log N) to insert it to proper position using similar binary search.
Option two - use Java Set. O(log N) for .contains() call + you'll have to call .contains() for each element of the variation, so we have O(|V| * log N), where |V| is variation size. You also add elements for O(log N).
Decision: I'd choose java set, because there is much fever code to write and you do not need to debug code that search/add element.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
For example, I have an array with the following contents:
a, b, c, d, e, f
I want the result to be:
b, c, d, e, f, a
How do I do this?
Use arraycopy :
var t = arr[0];
System.arraycopy(arr, 1, arr, 0, arr.length-1);
arr[arr.length-1] = t;
The javadoc specifies this operation is safe :
If the src and dest arguments refer to the same array object, then the
copying is performed as if the components at positions srcPos through
srcPos+length-1 were first copied to a temporary array with length
components and then the contents of the temporary array were copied
into positions destPos through destPos+length-1 of the destination
array.
Collections.rotate(Arrays.asList(array), -1);
try using ArrayList, it has some nice methods which shifts automatically. try
myArrayList.add(0,myArrayList.remove(myArrayList.size()-1))
LinkedList can do this fast, but you don't need to do this in most cases. Instead, defining a start index is much easier without modifying the content of the array.
For example,
int start = 5;
for (int i=start, j=0; j<arr.length; i++, j++) {
if (i == arr.length) {
i = 0;
}
// do something with arr[i]
}
copying array is another solution, but if you rotate the array frequently, I suggest not to change the content or creating new arrays, by defining a start index, you can change the start point whenever you want.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
What is the easiest way to find the largest and smallest element in an array and print its index location without using an algorithm. Is there a way to do it using a loop or if statement as i am new to java and it is as far as my knowledge goes for now.
This is my code for the array:
import java.io.*;
public class Tut2ArraysQ4
{
public static void main(String [] args) throws IOException
{
BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in));
int []item=new int[5];
for (int i = 0; i < item.length; i++)
{
System.out.println("Enter a number: ");
int num=Integer.parseInt(kbd.readLine());
System.out.println("Index " + i + " Contains Number " + num);
}
}//end class
}//end main
i am grateful for your help
You declare two variables equal to the element in the first position of your array, and two equal to the first position.
int min = array[0];
int max = array[0];
int posMin = 0;
int posMax = 0;
Make a for to iteration over all position of the array:
for(all the position of the array)
// if current position bigger than max
// max = element of the array in the current position
// posMin = current position
// if current position smaller than min
// min = element of the array in the current position
// posMax = current position
Another approach is sorting the array, the smallest element will be in the first position and the biggest on the last position of the array. However, this solution takes typically N lg N while the first one I post performance in N. If you are using radix sort it will take k N, but:
Sometimes k is presented as a constant, which would make radix sort
better (for sufficiently large n) than the best comparison-based
sorting algorithms, which are all O(n·log(n)). However, in general k
cannot be considered a constant.
read more about
I'm sorry, but unfortunately, There is no way to do what you're trying to do without using an Algorithm.
Even if you pick 2 numbers and prey that you're right, you'll be using an algorithm.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
How would I sort a char array in Java? I know I can use java.util.Arrays.sort(), but if I manually want to sort it? Using bubble sort or something?
Notice the string is "cab", the sorted result should be "abc". I don't know how to sort this, i know how to sort integers, but i don't know how to sort char arrays.
Here's my code:
String s1 = "cab";
char[] arr;
arr = s1.toCharArray();
//Could use
//java.util.Arrays.sort(arr);
//But want to do it manually using something like bubble sort
s1 = new String(arr);
characters can be directly compared as the comparison operators are overloaded. w>q i.e
arr[1]>arr[0]
is valid and gives true. So just treat them like integers in the bubble sort algorithm.
Using bubble sort or something?
Yes, a bubble sort would work. Or you could use any one of the other well-known sort algorithms; e.g. as listed in this Wikipedia page ... or any good textbook on data structures and algorithms.
(But no, I'm not going to code this for you.)
I have no idea weather this solution is the best way, and to be honest I don't think it is.
But I'v made a little piece of code which sorts an array in the following steps:
Make a for loop that goes from 0 to array.size() * array.size().
Make a index variable (int) which is 0 out side the loop
in the loop add a try catch and catch OutOfBoundsException, in the catch set index to 0.
In the try you get 'index' of your array,
char c = array[index]
And compare to index +1
c.compareTo(array[index +1])
If that's a positive number >0 you switch the two items' positions array[index] and array[index + 1]
If it doesn't make sense to you I can provide a code sample, but not before 2 hours from now, approximately..
This is what I meant:
public static ArrayList<mContact> SortByName(ArrayList<mContact> arr)
{
int i = 0;
for (int o = 0; o < arr.size() * arr.size(); o++)
{
try
{
int c = arr.get(i).getName().compareTo(arr.get(i + 1).getName());
if (c > 0)
{
mContact con = new mContact(arr.get(i).getName());
arr.get(i).setName(arr.get(i+1).getName());
arr.get(i+1).setName(con.getName());
}
i++;
}
catch (IndexOutOfBoundsException ex)
{
i = 0;
}
}
return arr;
}
That sorts the List by the contacts Name in ascending order.
The compareTo Method returns a integer that represents the diffrence of the two strings. and 0 if they are the same!
You can compare ASCII values of each of the characters or convert each of the to int using parseInt and compare their values.