Counting elements list without duplicates in Poly/ML programming - ml

I'm stuck on this exercise of functional programming in Poly/ML:
Do a function of type ''a list -> int so that it takes a list of ''a elements as argument. The function has to return the number of elements in the list without counting duplicates.
I really have no idea about how to solve it.
Thanks in advance for the help!

Reformulate that a little bit: "the number of unique elements in the list", which is "the length of the list after you have removed duplicates".
You probably already know how to find the length of a list, so that's one subproblem solved.
Now you have "remove duplicate elements from a list" left, which I leave as an exercise.
("Remove one particular value from a list" is probably a good step to include.)

Related

Selection Sort using a pointer and without loops

I am trying to use a recursive function to sort an array in ascending order. The catch is I can't use any for, while, or do/while loops. There are plenty of selection sort resources online but I'm having difficulty finding anything without loops and also including a pointer.
A short step-by-step of what I'm trying to do.
Place the marker at the first element of the array
2.If the marker is pointing at the last element of the array, then stop. Otherwise continue
3.Find the smallest element to the right of the marker
4.If this element is smaller than the element the marker is pointing at, then swap
5.Advance the marker to the next element to the right
6.Go to step 2
At the very least, you can design it using loops, and convert the loops.
Any loop can be converted into the following form:
State state = init();
while (cond(&state))
body(&state);
tail(&state);
And this loop be implemented trivially using recursion.
void recursive(State *state) {
if (!cond(state))
return;
body(state);
recursive(state);
}
State = state = init();
recursive(&state);
tail(&state);
That said, it's a lot easier to tackle this problem head on.
Selection sort is trivial to implement using recursion. As a whole, you are repeatedly sorting an ever shrinking portion of the array. After swapping the first element for smallest element, you need to sort the remainder of the array, which can easily be done using a recursive call.
That leaves the loop to find the smallest element of the array. Again, this is trivial to define in terms of itself. The smallest element of a list is the smallest of first element and the smallest element of the remainder of the list.

How do I iterate through one array and move every other element to two new arrays in Swift?

I do realize similar questions have been asked before, I looked at them before seeking help. But they were either not in Swift or too complex for me to decipher. My question is different from How do I shuffle an array in Swift? in that I have already done some of the work, like shuffling. The title was actually different from the question asked, which was "How do I randomize or shuffle the elements within an array in Swift?" I am only interested in iterating the resulting array and I couldn't separate that part from the rest of the code in the answers given for a question that encompassed so much more. That said, there are some great suggestions on that page so I think people like me will benefit from having both pages available. Maybe someone can set up a reciprocal link on that page as I have done here.
Admittedly, I am new to Swift and not a seasoned programmer in any language, but please don't assume I am coming here seeking help without trying to figure it out on my own. I am spending many hours learning the fundamentals of all C based languages and reading the Swift literature at developer.apple.com.
So the question will be more obvious, I and attempting to build the card game War. Thus far I have accomplished constructing the (an array) deck of cards and randomized it (shuffled). I am stuck at looping through the resulting array of 52 objects and assigning (moving) them to the two players hands (two new arrays). I'm not sure how much of my code I should display in order to help me but if you need more, I'll gladly provide it. Please note that this is only an exercise, practice for me to learn how to write complex programs, and some code, like the function to randomize, is not mine, I found it right here at stackoverflow. I'd almost prefer if you didn't just hand me the code that will work, I'm not likely going to learn as much that way, but if providing steps in plain English so I can figure out the syntax is too much trouble, so be it, provide an example, I'm sure I'll get plenty of chances to write/use the syntax later.
One more note, I'm only working in a playground at the moment, when and if I can get all the code working, I'll move to the UI stuff.
Thanks in advance, Rick
/* Skipping past everything I did to get here,
the array (shuffledDeck) has 52 shuffled cards (elements) in it.
The array is NSMutableArray and contains strings like
2Hearts, 5Spades, 14Clubs, etc. Each suit has 14 cards.*/
shuffledDeck
// create vars to hold shuffled hands
var playerOneHand = []
var playerTwoHand = []
/* Started a for loop to assign cards to each hand
but don't know which method(s) is/are best to use
to remove the first or last card and alternately
append (move) it to the (hopefully) initialized
variables playerOneHand and PlayerTwoHand.
Optionally, since the cards are already shuffled,
I could just split the deck using the range method,
whichever is easier. I tried and failed at both ways.*/
var i = 0
for dealtCard in shuffledDeck {
}
var shuffledDeck:[String] = ["2Hearts", "5Spades", "14Clubs", "etc"]
//shuffledDeck will of course be your shuffled deck
var playerOneHand:[String] = []
var playerTwoHand:[String] = []
for (index, cardString) in enumerate(shuffledDeck) {
if index % 2 == 0 {
playerOneHand.append(cardString)
}else{
playerTwoHand.append(cardString)
}
}
I’m looping through every item in the shuffledDeck, but with that I use the index of the array to get a number. I use this number to see if that number devided by 2 is equal to 0 (the number is even) or not (uneven) if a number is even, I get the item that is in the array at the given index and add that item to the hand of player one. If the index is uneven I add the item to the second player’s hand. This means the first item goed to player one’s hand, the second item goes to the hand of the second player. the third Item goes back to the first player and so on.
As mentioned by Martin R you can use the range method to assign the first half of the deck to the first player and the second to the second player as follow:
let cards:[String] = ["2♦️","3♦️","4♦️","5♦️","6♦️","7♦️","8♦️","9♦️","T♦️","J♦️","Q♦️","K♦️","A♦️","2♠️","3♠️","4♠️","5♠️","6♠️","7♠️","8♠️","9♠️","T♠️","J♠️","Q♠️","K♠️","A♠️","2♥️","3♥️","4♥️","5♥️","6♥️","7♥️","8♥️","9♥️","T♥️","J♥️","Q♥️","K♥️","A♥️","2♣️","3♣️","4♣️","5♣️","6♣️","7♣️","8♣️","9♣️","T♣️","J♣️","Q♣️","K♣️","A♣️"]
extension Array {
var shuffled:[T] {
var elements = self
for index in 0..<elements.count - 1 {
swap(&elements[index], &elements[Int(arc4random_uniform(UInt32(elements.count - 1 - index))) + index])
}
return elements
}
}
let cardsShuffled = cards.shuffled
let playerOneHand = cardsShuffled[0...25]
let playerTwoHand = cardsShuffled[26...51]
Note: The shuffle extension was created using this answer as reference

Sort a linked list

want to sort a linked list, but my code doesnt want to:)
Here it is:
void swap(element *p,element*q) {
int aux;
aux=p->info;
p->info=q->info;
q->info=aux;
}
void ordonare(element *lista) {
element *p,*q;
for(p=lista; p!=NULL; p=p->urmator) {
if(p->info>p->urmator->info) {
swap(p,p->urmator);
}
}
}
If this works, it will only sort the values, without changing the nodes' positions.
I can't seem to find the bug here, and I would appreciate if you could also indicate the solution where the nodes will change their positions.
Thanks,
Radu
UPDATE
the code above works, but as #Daniel.S mentioned, it only does one iteration through the list.
What conditions am I supposed to put in order to iterate until it is sorted?
Thanks!!:)
Look up merge sort, it is perfect for lists and easy to implement. That link has an example implementation:
Merge sort is often the best choice for sorting a linked list: in this situation it is relatively easy to implement a merge sort in such a way that it requires only Θ(1) extra space, and the slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible.
Your sorting algorithm is not complete. You're missing parts in the loop. One loop iteration over the list is not enough. Example:
You have the list {3,2,1}. If you sort it with your algorithm, it will first compare 3 and 2 and swap them, then you get
{2,3,1} it will then compare 3 and 1 and swap those, too. Then you get {2,1,3}. Your algorithm finishes here, but the list isn't sorted yet.
Depending on the algorithm you want to implement (e.g. bubble sort), you have to add additional code.
What algorithm do you want to implement?

Rearraging a rotated sorted array

I have seen several questions related to rotated sorted-arrays e.g. for searching for the pivot element or searching for an element in such an array.
However I did not find any question related to rearranging such an array to its original form without using sorting.
So my question: *Is there an efficient way, or trick, to rearrange a rotated, sorted-array to original form without using extra memory?
Heres what I would do..
I would find the starting element using a variation of binary search.
Once that is found , if you can use external memory, it can be done in O(n)
So the total time is O(lgn) + O(n) which is O(n)
Specifically to rotation: Seeing ajay's comments, I agree that since we have to rotate in place, the best option is bubble sort. Which is O(n*m) where m is number of elements rotated.
But if we can use some storage to keep the elements on either side of the starting element, basically, if we can use external memory, it just is a question of putting each element in the right place in the new array.

Add element to next unused index - C

I'm sure others have already asked this, but is it possible to insert an element into the next available index of an array without using a for-loop to find that index first? Almost like a list.add() function but for arrays in C.
no, you will have to loop through the array.
If it's really list functionality you want you could implement a simple linked list instead of using arrays, for example like this: http://www.cprogramming.com/tutorial/c/lesson15.html

Resources