Matlab - sorting a matrix - sorting

I think I can illustrate this best with an example:
Suppose I have A = [ 1, 4, 2, 3;
0,-1, 2, -1]
I want to turn it into
[1, 2, 3, 4;
0, 2, -1, -1]
i.e. keep columns intact, sort by entries in first row. How do I do this?

The sortrows command does what you want:
>> A = [ 1, 4, 2, 3; 0,-1, 2, -1];
>> sortrows(A.').'
ans =
1 2 3 4
0 2 -1 -1
You can also use the second return value from sort to get the column permutation necessary to turn your matrix into the one you want:
>> [~,ii] = sort(A(1,:))
ii =
1 3 4 2
>> A(:,ii)
ans =
1 2 3 4
0 2 -1 -1

Related

Printing the process of a recursive backtracking problem

I have been given this assignment for school:
You have been given a puzzle consisting of a row of squares each containing an integer, like this:
6, 4, 1, 3, 3, 1, 4, 1, 1, 0
The bold number on the initial square is a marker that can move to other squares along the row.
At each step in the puzzle, you may move the marker the number of squares indicated by the integer in the square it currently occupies.
The marker may move either left or right along the row but may not move past either end.
The goal of the puzzle is to move the marker to the 0 at the far end of the row.
The program checks the index you are currently on, and moves either left or right a number of squares based on the integer at that index in the array. It decides this based on the bounds of the array, if it can't move the required number of squares to the left it will move to the right, and vice versa.
In this program, the first move has to be 6 to the right, since it cannot move 6 spaces left without going out of bounds. Then, it has to move 4 left since it cant move 4 right, and it goes on like that.
I have got this working, and printing the process is worth extra credit. I have it printing the process, but it is out of order.
here is my code:
def self.solvable(start, board)
return false if start>= board.length || start<0
return false if ##infinite[start] == -1
return true if board[start] == 0
##infinite[start] = -1
if solvable(board[start] + start, board)
puts "Shifted right " + board[start].to_s + " spaces, from index " + start.to_s + " to index " + (board[start] + start).to_s
return true
else
puts "Shifted left " + board[start].to_s + " spaces, from index " + start.to_s + " to index " + (start - board[start]).to_s
end
return solvable(start - board[start], board)
end
print "Enter an array of numbers: "
input = gets.chomp!
board = input.each_char.map(&:to_i)
##infinite = input.each_char.map(&:to_i)
puts solvable(0, board)
I do not understand how to make the code output in a more logical order, printing 6 spaces right, 4 spaces left, etc... instead of the current output, which is:
Shifted left 4 spaces, from index 6 to index 2
Shifted left 3 spaces, from index 3 to index 0
Shifted left 1 spaces, from index 2 to index 1
Shifted left 1 spaces, from index 5 to index 4
Shifted right 1 spaces, from index 8 to index 9
Shifted right 1 spaces, from index 7 to index 8
Shifted right 3 spaces, from index 4 to index 7
Shifted right 4 spaces, from index 1 to index 5
Shifted right 6 spaces, from index 0 to index 6
Assumption
I assume the game begins at position 0. Each move increases or decreases the position by an integal amount. The objective is to get back to position 0 after the first move has been made.
We are given an array, arr, of integers and a mapping from positions to indices of the array. For position p the index of arr is given by p % arr.size.
If we are at position p we obtain the value may move to position p + n or p - n, where
n = arr[p % arr.size]
For the example given:
arr = [6, 4, 1, 3, 3, 1, 4, 1, 1, 0]
(arr.size #=> 10) and p initially zero,
n = arr[0 % 10]
#=> arr[0] => 6
so we may move to position +6 or -6. If we move to +6, we calculate
n = arr[6 % 10]
#=> 4
so we may move to position 6+4 #=> 10 or 6-4 #=> 2. If we move to -6, we calculate
n = arr[-6 % 10]
#=> 3
so we may move to position -6-3 #=> -9 or -6+3 #=> -3.
Note that arr[9] #=> 0 can be regarding as an absorbing state.
Code
The method I've chosen to use is recursive.
def onward_to_zero(arr, pos=0)
n = arr[pos % arr.size]
return [] if n.zero?
return [-n] if (pos-n).zero?
return [n] if (pos+n).zero?
if rand < 0.5
rv = onward_to_zero(arr, pos-n)
return [-n] + rv unless rv.empty?
rv = onward_to_zero(arr, pos+n)
return [n] + rv unless rv.empty?
else
rv = onward_to_zero(arr, pos+n)
return [n] + rv unless rv.empty?
rv = onward_to_zero(arr, pos-n)
return [-n] + rv unless rv.empty?
end
[]
end
I believe it can be proven that there is always a path back to zero, but I have not given thought to a proof.
Examples
arr = [6, 4, 1, 3, 3, 1, 4, 1, 1, 0]
onward_to_zero(arr)
#=> [-6, 3, 1, -1, 1, -1, -1, 4]
# pos % 10 0 4 7 8 7 8 7 6
# pos-> 0 -6 -3 -2 -3 -2 -3 -4 0
arr = [3, 2, 4, 1, 3, 6, 2]
onward_to_zero(arr)
#=> [3, -1, 4, 2, 2, 1, -3, 2, -1, -4, -6, -2, 3]
# pos-> 3 2 6 8 10 11 8 10 9 5 -1 -3 0
arr = [3, 3]
onward_to_zero(arr)
#=> [-3, 3]
# pos-> -3 0
arr = [7, 26, 33, 18, 7, 13]
onward_to_zero(arr)
#=> [-7, -13, 7, 13]
# pos-> -7 -20 -13 0
Discussion
Notice that if rand < 0.5 causes me to consider a reduction in the position before an increase in the position roughly half the time. If I were always to consider a reduction before an increase, or vice-versa, I could easily get a stack level too deep error.
Even with that probability mechanism, however, the method gives quite varied results and could still result in a stack level too deep error. Here are the results I obtained by running the first example 10 times.
[6, -4, 1, -3]
[-6, 3, 1, -1, -1, 4]
[6, 4, 6, 4, 6, 4, 6, 4, 6,..., -1, -1, 4] (824 elements)
[6, 4, -6, -3, 4, 1, -4, -1,..., -4, 1, -3] (386 elements)
[-6, 3, 1, -1, -1, 4]
[-6, -3, 4, 1, 4]
[-6, 3, 1, -1, 1, -1, -1, 4]
[-6, -3, -4, -1, -4, 1, -3, 6, 4, 6, 4]
[-6, -3, -4, 1, -1, -1, -4, -1, 4, 1, 4, 6, 4]
[-6, 3, -1, 4]

octave use vector as columns index for a matrix

I've a vector y = [1; 1; 2; 3] and a matrix Y = zeros(4, 3).
I need to set to 1 the columns in Y that corresponds to values of the vector y. i.e.
Y = [1, 0, 0; 1, 0, 0; 0, 1, 0; 0, 0, 1]
Y(y) or Y(:, y) does not give me the result I need!
Any idea how I could achieve this?
You need to convert those columns indices into linear indices. You do it like so:
octave:1> A = zeros (4, 3);
octave:2> c_sub = [1, 1, 2, 3];
octave:3> ind = sub2ind (size (A), 1:rows(A), c_sub)
ind =
1 2 7 12
octave:4> A(ind) = 1
A =
1 0 0
1 0 0
0 1 0
0 0 1
However, if your matrix is that sparse, do create a proper sparse matrix:
octave:4> sparse (1:4, c_sub, 1, 4, 3)
ans =
Compressed Column Sparse (rows = 4, cols = 3, nnz = 4 [33%])
(1, 1) -> 1
(2, 1) -> 1
(3, 2) -> 1
(4, 3) -> 1
and maybe consider using a logical matrix (use false instead of zeros and true instead of 1.

How to find the index of a k-permutation from n elements?

I know that, for a k-permutation p of size k, built from n elements, there are:
P(n, k) = n! / (n - k)!
possible k-permutations. For example:
k = 2
n = 4
l = [1, 2, 3, 4]
P(n, k) = 4! / (4 - 2)! = 12
1 2 | 2 1 | 3 1 | 4 1
1 3 | 2 3 | 3 2 | 4 2
1 4 | 2 4 | 3 4 | 4 3
And yet another example:
k = 3
n = 4
l = [1, 2, 3, 4]
P(n, k) = 4! / (4 - 3)! = 24
1 2 3 | 2 1 3 | 3 1 2 | 4 1 2
1 2 4 | 2 1 4 | 3 1 4 | 4 1 3
1 3 2 | 2 3 1 | 3 2 1 | 4 2 1
1 3 4 | 2 3 4 | 3 2 4 | 4 2 3
1 4 2 | 2 4 1 | 3 4 1 | 4 3 1
1 4 3 | 2 4 3 | 3 4 2 | 4 3 2
So, how do I find the index of the k-permutation p? Consider the permutations
to be generated lexicographically.
Edit:
I could start by finding in which "block" p is, addressing the block by the first element of p. For example, for p = [3, 2, 4], the index for p should be at least 12 (counting from 0 to P(n, k) - 1).
But then, to find the second element inside that "block", I'd have to see what are the remaining items to be found, and in which position they will be. I mean, I'd be eventually addressing the list [1, 4], and 4 would be at position 2, so simply using the element as key would require some extra manipulation.
I could use a hash to look up the elements and update their positions, but it'd give me a O(n^2) time complexity. Is it possible to do any better?
The number of permutations for a given digit in a given position is given by a formula
(n-digit position)! / (n-k)! where digit position starts on the left with 1.
To get the number of preceding permutations for a given permutation (that is, its index), multiply the formula for each digit by the number of preceding digits not already used, and add them up.
Example 1, k = 2, n = 4, p = [3,4]
First digit, 3:
(4-1)! / (4-2)! * (number of unused preceding digits, 2) = 6
There are six permutations preceding the first that has 3 in position 1.
Second digit, 4:
(4-2)! / (4-2)! * (number of unused preceding digits, 2) = 2
There are two permutations preceding the first that has 4 in position 2.
Zero based index: 6 + 2 = 8.
Example 2, k = 3, n = 4, p = [3,2,4]
First digit, 3:
(4-1)! / (4-3)! * (number of unused preceding digits, 2) = 12
There are 12 permutations preceding the first that has 3 in position 1.
Second digit, 2:
(4-2)! / (4-3)! * (number of unused preceding digits, 1) = 2
There are two permutations preceding the first that has 2 in position 2.
Third digit, 4:
(4-3)! / (4-3)! * (number of unused preceding digits, 1) = 1
There is one permutation preceding the first that has 4 in position 3.
Zero based index: 12 + 2 + 1 = 15.
TXR language:
$ txr -p "(pos '(1 4 3) (perm '(1 2 3 4) 3))"
5
It is brute force, however; of course pos knows nothing about the structure of permutations.
Use binary search tree (BST). Store all you numbers in it before you start and delete them after you use one. To find x-th element maintain .subtreeSize for every vertex and just descend the tree to find the number you need. Pseudocode:
def findXth(x):
curVertex = BST.root
while:
curPosition = curVertex.leftChild.subtreeSize
if curPosition == x: return curVertex.value
elif curPosition > x: curVertex = curVertex.leftChild
elif curPosition < x: curVertex = curVertex.rightChild
Don't forget to check for vertices existence and to delete the vertex you find.
Overall complexity is going to be O(n log n).
you can reference below function
/**
* list all k or <=k size permutation of a given list with n unique elements.
* n can be bigger than 64. this function will take O(K^N) time, Bad.
*
* #param uniqueList
* #param permutationSize
* #param permutation
* #param only Only show the permutation of permutationSize,
* else show all permutation of less than or equal to permutationSize.
*/
public static void my_permutationOf(List<Integer> uniqueList, int permutationSize, List<Integer> permutation, boolean only) {
if (permutation == null) {
assert 0 < permutationSize && permutationSize <= uniqueList.size();
permutation = new ArrayList<>(permutationSize);
if (!only) {
System.out.println(Arrays.toString(permutation.toArray()));
}
}
for (int i : uniqueList) {
if (permutation.contains(i)) {
continue;
}
permutation.add(i);
if (!only) {
System.out.println(Arrays.toString(permutation.toArray()));
} else if (permutation.size() == permutationSize) {
System.out.println(Arrays.toString(permutation.toArray()));
}
if (permutation.size() < permutationSize) {
my_permutationOf(uniqueList, permutationSize, permutation, only);
}
permutation.remove(permutation.size() - 1);
}
}
E.g. you can think the element is the index
public static void main(String[] args) throws Exception {
my_permutationOf(new ArrayList<Integer>() {
{
add(0);
add(1);
add(2);
add(3);
}
}, 3, null, true);
}
the result is
[0, 1, 2]
[0, 1, 3]
[0, 2, 1]
[0, 2, 3]
[0, 3, 1]
[0, 3, 2]
[1, 0, 2]
[1, 0, 3]
[1, 2, 0]
[1, 2, 3]
[1, 3, 0]
[1, 3, 2]
[2, 0, 1]
[2, 0, 3]
[2, 1, 0]
[2, 1, 3]
[2, 3, 0]
[2, 3, 1]
[3, 0, 1]
[3, 0, 2]
[3, 1, 0]
[3, 1, 2]
[3, 2, 0]
[3, 2, 1]

Generate a new array from an array of numbers

I found this question on Glassdoor:
Generate a new array from an array of numbers. Start from the beginning. Put the number of some number first, and then that number. For example, from array 1, 1, 2, 3, 3, 1 You should get 2, 1, 1, 2, 2, 3, 1, 1 Write a program to solve this problem.
I am not sure if I get the idea, how come 1, 1, 2, 3, 3, 1 transforms into 2, 1, 1, 2, 2, 3, 1, 1? I first thought they are number of occurrences of a number followed by the number itself. But from the given example, it seems like something else is wanted.
What is this transformation?
I first thought they are number of occurrences of a number followed by the number itself.
Your first thought was correct.
Break the first array down to be:
1, 1,
2,
3, 3,
1
And the second to be:
2, 1,
1, 2,
2, 3,
1, 1
Then it should make more sense.
Sample implementation:
#!/usr/bin/env python
import sys
array = map(int, sys.argv[1:])
print array
count = 0
current = array[0]
index = 1
output = []
for number in array:
if current != number:
output.append(count)
output.append(current)
current = number
count = 0
count += 1
output.append(count)
output.append(current)
print output
Demo:
> ./arrays.py 1 1 2 3 3 1
[1, 1, 2, 3, 3, 1]
[2, 1, 1, 2, 2, 3, 1, 1]
what u think is correct. its the number of times the distinct element comes and then the element itself.
here is pseudocode:
array1 = given input array
array2 = output array
int previous = array1[0];
int currentCount = 0;
for each entry x in array1 {
if(x == previous) {
currentCount++;
}
else {
array2.add(currentCount);
array2.add(x);
//reset global variables for next elements
previous = x;
currentCount = 0;
}
}
And the Haskell version...yup, that's the whole thing.
import Data.List
countArray list = concat [[length l, fromIntegral (head l)] | l <- group list]

Balanced layout of n items in a grid

I have a list of n logos to display in a grid, with a maximum of 3 per row.
What's an algorithm to decide how many to display per row such that the number of logos per row is as balanced as possible without using more than the minimum possible number of rows?
For example:
n -> number in each row
1 -> 1
2 -> 2
3 -> 3
4 -> 2, 2
5 -> 3, 2
6 -> 3, 3
7 -> 3, 2, 2
8 -> 3, 3, 2
9 -> 3, 3, 3
10 -> 3, 3, 2, 2
For N <= 3 just use N.
If N is exactly divisible by 3 then use: 3 3 ... 3
If N when divided by 3 has remainder 1 then use: 3 3 ... 2 2
If N when divided by 3 has remainder 2 then use: 3 3 ... 3 2
AS confusing as your question is, I think what you need to do is first determine:
number_of_rows = ceil(number_of_logos / 3.0)
Then add a logo to each row, one at a time.
Python:
import math
def partition_logos(count, lsize):
num_lines = int(math.ceil(count / float(lsize)))
partition = [0] * num_lines
for i in xrange(count):
partition[i%num_lines] += 1
return partition
>>> for i in xrange(1,11):
... print partition_logos(i, 3)
[1]
[2]
[3]
[2, 2]
[3, 2]
[3, 3]
[3, 2, 2]
[3, 3, 2]
[3, 3, 3]
[3, 3, 2, 2]
A recursive solution, in Python:
def logos_by_row(N, rows):
width = 0
if N > 4 or N == 3:
width = 3
elif N == 4 or N == 2:
width = 2
elif N == 1:
width = 1
if width != 0:
rows.append(width)
logos_by_row(N - width, rows)
answer = []
for i in range(10):
logos_by_row(i+1, answer)
print answer
just use n/3 to calculate the row and n%3 to calculate the column
edit: ok i saw you edited your question.... i din't saw that you want to display 2 in each row if the are 4 logos. but then you can use n mod 3 to calculate if their is a reminder as others already suggested
if n%3 = 0 then just put 3 logos in each row
if n%3 = 1 then put the last 4 logos in two rows
if n%3 = 2 then put 3 logos in n row and the last 2 logos in a separate row

Resources