So i need to write a program that merges two sorted lists into a new third sorted list and I can ONLY use operations of the ADT sorted list.
As with all my other assignments I start with pseudocode but I am in a funk tonight and can't wrap my head around some pseudocode for this.
I have written some pointers though: Create a new sorted list; while the two lists are not empty remove and compare them, to add one or the other to the new list. Stop when the lists are empty (but do think about what happens when one becomes empty before the other!).
Any and all help is very appreciated
EDIT: To let you know I am just looking for Pseudocode help NOT actual code
function merge (lista, listb) {
toReturn = your 'third list'
while lista and listb both still have elements {
if lista's smallest element < listb's smallest element {
add lista's smallest element to toReturn
remove lista's smallest element
} else {
add listb's smallest element to toReturn
remove listb's smallest element
}
}
// if lista has no elements, this loop is skipped
while lista still has elements {
add them to toReturn
}
// if listb has no elements, this loop is skipped
while listb still has elements {
add them to toReturn
}
return toReturn
}
this can be done by using merge procedure of merge sort
this is my cde where i have passed all the 3 list from main function
public static void merge(int A[],int A1[],int B1[],int n1,int n2)
{
int a[]=new int[n1+1];
int b[]=new int[n2+1];
for(int k=0;k<n1;k++){
a[k]=A1[k];
}
for(int k=0;k<n2;k++){
b[k]=B1[k];
}
int i=0,j=0;
a[n1]=Integer.MAX_VALUE;
b[n2]=Integer.MAX_VALUE;
for(int k=0;k<A.length;k++){
if(a[i]>b[j]){
A[k]=b[j];
j++;
}
else{
A[k]=a[i];
i++;
}
}
}
Related
New to rust. And I'm stuck.
I have a Vec of Vec of &str (basically a collection of CSV rows, each row is Vec of &str).
I want to iterate over the whole collection, and conditionally change some cell values.
I have tried some approaches with iterator and enumeration() to operate with index.
But in the end, I always have this error -> error[E0499]: cannot borrow *row as mutable more than once at a time.
And I can't really find how to do it. What's the workaround?
//iterate over the collection of rows
for row in &mut raw_data_rows[0..] {
//iterate over row cells
for item in &mut row[0..] {
//if cell == "n/a"
if item.to_string() == "n/a" {
//change it to something else
todo!(); //change the value of the item
}
}
}
Thank you in advance.
I cannot see any problem with that.
I just made the iterations explicit with .iter_mut().
Note that I'm not certain &str is what you want here.
Using String would allow mutating their content, not just replacing them.
As requested in a comment, here is why I find these iterations explicit :
v.iter_mut() means « at each iteration I want to obtain an exclusive (mutable) reference to the next element ».
v.iter() means « at each iteration I want to obtain a shared (non-mutable) reference to the next element ».
v.into_iter() means « at each iteration I want to consume/extract the next element » (v should not be usable after that).
Iterating directly on v implicitly calls v.into_iter() which should consume the elements but if v is not a value but a reference to a container, this will behave as v.iter() which is quite confusing in my opinion.
That's why I try to always be explicit about my intention when I iterate over a sequence.
fn main() {
let mut raw_data_rows = vec![
vec!["aa", "bb", "cc"],
vec!["dd", "n/a", "ee"],
vec!["ff", "gg", "hh"],
];
for row in raw_data_rows.iter_mut() {
for item in row.iter_mut() {
if *item == "n/a" {
*item = "NEW_ITEM"
}
}
}
println!("{:?}", raw_data_rows);
}
/*
[["aa", "bb", "cc"], ["dd", "NEW_ITEM", "ee"], ["ff", "gg", "hh"]]
*/
I have a List<String> and I want to create a square matrix (2-dimensional array/list) of Set<String> with the same dimensions as the length of the List<String>.
I tried using
List.filled(entries.length, List.filled(entries.length, Set<String>()));
but the problem is that it seems that each row of my matrix refers to the same list instance, so changing a value in one row changes it in all the others as well.
So then I tried
List.filled(entries.length, List.from(List.filled(entries.length, Set<String>())));
but I still have the same problem. Eventually I surrendered and resorted to
List<List<Set<String>>> matrix = [];
for(int i=0; i<entries.length; i++) {
List<Set<String>> row = [];
for (int n = 0; n<entries.length; n++) {
row.add(Set<String>());
}
matrix.add(row);
}
It works, but it's ugly. Is there a cleaner way to do this?
List.generate(n, (_) => List.generate(n, (_) => <String>{}));
Probably, you could use Matrix2 class (or matrixes with other dimensions: Matrix3, Matrix4). Unfortunately, I have no experience in using these classes, but maybe it has a sense for you. These classes have constructors for generating matrix from lists.
I have a treetableview which multiple columns. I like to order only by one column so I apply:
treetbvItems.getSortOrder().add("categoria");
This order data by column "categoria" alphabetical but I want to apply my custom order.
For example, if category can be onew of this values: animals, computers, shoes, vehicles... with above sentence, I get tree order by this way:
animals
computers
shoes
vehicles
but if I want (can be any other custom orther):
computers
shoes
animals
vehicles
Is possible or not to do whith JavaFX?
I assume you really mean
TreeTableColumn<String> categoria ;
// ...
treebvItems.getSortOrder().add(categoria);
since the code you posted won't compile.
You can control the ordering for a particular column by setting a Comparator on the column.
The Comparator defines a compareTo(String, String) method that returns an negative int if the first argument comes before the second, a positive int if the second argument comes before the first, and 0 if they are equal.
So you could do something like:
categoria.setComparator((cat1, cat2) -> {
if (cat1.equals(cat2)) {
return 0 ;
}
if ("computers".equals(cat1)) {
return -1 ;
}
if ("computers".equals(cat2)) {
return 1 ;
}
if ("shoes".equals(cat1)) {
return -1 ;
}
if ("shoes".equals(cat2)) {
return 1 ;
}
if ("animals".equals(cat1)) {
return -1 ;
}
if ("animals".equals(cat2)) {
return 1 ;
}
throw new IllegalArgumentException("Unknown categories: "+cat1+", "+cat2);
}
Note that if you have a fixed set of categories, you should probably use an Enum instead of a String. The "natural" order of an Enum is defined by its declaration order.
I have n integers and I need a quick logic test to see that they are all different, and I don't want to compare every combination to find a match...any ideas on a nice and elegant approach?
I don't care what programming language your idea is in, I can convert!
Use a set data structure if your language supports it, you might also look at keeping a hash table of seen elements.
In python you might try
seen={}
n_already_seen=n in seen
seen[n]=n
n_already_seen will be a boolean indicating if n has already been seen.
You don't have to check every combination thanks to commutivity and transitivity; you can simply go down the list and check each entry against each entry that comes after it. For example:
bool areElementsUnique( int[] arr ) {
for( int i=0; i<arr.Length-1; i++ ) {
for( int j=i+1; j<arr.Length; j++ ) {
if( arr[i] == arr[j] ) return false;
}
}
return true;
}
Note that the inner loop doesn't start from the beginning, but from the next element (i+1).
You can use a Hash Table or a Set type of data structure that using hashing. Then you can insert all of the elements into the hashtable or hashset, and either as you insert, check if the element is already in the table/set. If for some reason you don't want to check as you go, you can just insert all the numbers and then check to see if the size of the structure is less than n. If it is less than n, there had to be repeated elements. Otherwise, they were all unique.
Here is a really compact Java solution. The time-complexity is amortized O(n) and the space complexity is also O(n).
public boolean areAllElementsUnique(int [] list)
{
Set<Integer> set = new HashSet<Integer>();
for (int number: list)
if (set.contains(number))
return false;
else
set.add(number);
return true;
}
Good Morning stackoverflow...
I'm having a problem.... this is my sample code
var i:Number = new Number();
trace("showarray length" + showArray.length);
for(i=0;i<showArray.length;i++){
trace("equal daw" + showArray.getItemAt(i).id + "==" + num);
if(showArray.getItemAt(i).id == num){
showArray.removeItemAt(i);
}
}
trace('alerts');
myproblem here is...wherenever the if is satisfied it stops looping it immediately goes out of the loop
this is a sample output
given that the length of showArray is 2 and num = 0
showarray length2
equal daw0==0
alerts
please help me
If you want to remove items while iterating over array, iterate in reverse order. This way element removal does not affect cycle condition:
for (var i:int = showArray.length - 1; i >= 0; i--) {
if (someCondition) {
showArray.removeItemAt(i);
}
}
Another small bonus that this is slightly faster, as it doesn't call showArray.length on each step.
An even better way might be to use the filter method of the Array class.
array = array.filter(function (e:*, i:int, a:Array):Boolean {
return e.id != num;
});
When your if is satisfied for id == num (which is 0 so happening in the first loop) and the item is removed, your array length decreases to 1 so the loop won't run any more.
That's because you are removing items at the time you are iterating throught them.
array = [1, 2]
^ // pointer in first iteration
eliminate 1
array = [2]
^ // the pointer remains in the same location
//ups! out of the loop. all items were visited.
You can copy the array before you iterate through it and iterate the copy or mark the indices to remove and remove them later or iterate the array backwards.
PS: Sorry for my poor English.
After showArray.removeItemAt(i);, add i--;
Because you removed the item at index i from the array, the item that was at i + 1 got moved to i. By subtracting one, you ensure that the moved item doesn't get skipped.
alxx's answer is also a good solution.