swapping elements of a 2 dimensional vector c++ - vector

I have a matrix of the form
vector<vector<int>> K
which has size NxN. How can i swap two elements of this vector say K[i]k[j] with K[n-j][i]?
In general, how can i swap two elements of an 2D vector?

Because vector's [] operator returns a reference, a std::swap() will work. For example:
swap(K[i][j], K[n-i][i]);

The general swapping could look something like this
void swap(int& a, int& b)
{
int temp = a;
a = b;
b = tmp;
}
Then you call it with
swap(K[i][j], K[n - j][i]);
Or you can just call std::swap as #Jeffrey suggests

Related

How does "runif" function work internally in R?

I am trying to generate a set of uniformly distributed numbers in R. I know that we can use the function "runif" in R to do the same. But I really want to understand the idea behind how this function would have been developed. In the sense how does the code work for the function "runif". So, in a nutshell, I want to create my own function which can do the same task as the "runif"
Ultimately, runif calls a pseudorandom number generator. One of the simpler ones can be found here defined in C within the R code base and should be straightforward to emulate
static unsigned int I1=1234, I2=5678;
void set_seed(unsigned int i1, unsigned int i2)
{
I1 = i1; I2 = i2;
}
void get_seed(unsigned int *i1, unsigned int *i2)
{
*i1 = I1; *i2 = I2;
}
double unif_rand(void)
{
I1= 36969*(I1 & 0177777) + (I1>>16);
I2= 18000*(I2 & 0177777) + (I2>>16);
return ((I1 << 16)^(I2 & 0177777)) * 2.328306437080797e-10; /* in [0,1) */
}
So effectively this takes the initial integer seed values, shuffles them bitwise, then recasts them as double precision floating point numbers via multiplying by a small constant that normalises the doubles into the [0, 1) range.

How to find a pair of numbers in a list given a specific range?

The problem is as such:
given an array of N numbers, find two numbers in the array such that they will have a range(max - min) value of K.
for example:
input:
5 3
25 9 1 6 8
output:
9 6
So far, what i've tried is first sorting the array and then finding two complementary numbers using a nested loop. However, because this is a sort of brute force method, I don't think it is as efficient as other possible ways.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), k = sc.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
Arrays.sort(arr);
int count = 0;
int a, b;
for(int i = 0; i < n; i++) {
for(int j = i; j < n; j++) {
if(Math.max(arr[i], arr[j]) - Math.min(arr[i], arr[j]) == k) {
a = arr[i];
b = arr[j];
}
}
}
System.out.println(a + " " + b);
}
}
Much appreciated if the solution was in code (any language).
Here is code in Python 3 that solves your problem. This should be easy to understand, even if you do not know Python.
This routine uses your idea of sorting the array, but I use two variables left and right (which define two places in the array) where each makes just one pass through the array. So other than the sort, the time efficiency of my code is O(N). The sort makes the entire routine O(N log N). This is better than your code, which is O(N^2).
I never use the inputted value of N, since Python can easily handle the actual size of the array. I add a sentinel value to the end of the array to make the inner short loops simpler and quicker. This involves another pass through the array to calculate the sentinel value, but this adds little to the running time. It is possible to reduce the number of array accesses, at the cost of a few more lines of code--I'll leave that to you. I added input prompts to aid my testing--you can remove those to make my results closer to what you seem to want. My code prints the larger of the two numbers first, then the smaller, which matches your sample output. But you may have wanted the order of the two numbers to match the order in the original, un-sorted array--if that is the case, I'll let you handle that as well (I see multiple ways to do that).
# Get input
N, K = [int(s) for s in input('Input N and K: ').split()]
arr = [int(s) for s in input('Input the array: ').split()]
arr.sort()
sentinel = max(arr) + K + 2
arr.append(sentinel)
left = right = 0
while arr[right] < sentinel:
# Move the right index until the difference is too large
while arr[right] - arr[left] < K:
right += 1
# Move the left index until the difference is too small
while arr[right] - arr[left] > K:
left += 1
# Check if we are done
if arr[right] - arr[left] == K:
print(arr[right], arr[left])
break

How can I use `vector <unsigned int*> vec;` properly

I am new in C++ and I want to use vector <unsigned int*> vec;
I try this code:
vector <unsigned int*> vec;
unsigned int* tmpV= new unsigned int[4];
for(unsigned int i=0; i<4;i++){
tmpV[i]=i;
}
vec.push_back(tmpV);
unsigned int* tmpV2=vec.at(0);
cout<<"A) tmpV2[1]: "<<tmpV2[1] <<endl;
cout<<"vec.size(): "<<vec.size()<<endl;
for(unsigned int i=0; i<4;i++){
tmpV[i]=i+4;
}
vec.push_back(tmpV);
tmpV2=vec.at(0);
cout<<"vec.size(): "<<vec.size()<<endl;
cout<<"B) tmpV2[1]: "<<tmpV2[1]<<endl;
The problem her is that I wanted to output the same value for A) and B)
but it ouputs
A) tmpV2[1]: 1
B) tmpV2[1]: 5
I want to be able to handle different elements in this vector of pointers.
I can roughly understand why this is going on but I couldn't find a solution.
Have in mind that I don't want to use: vector < vector <unsigned int> >
It is because you have incremented the value pointed by the pointer at the index a in vector
vec
if you reprint it again after printing
valuecout<<"B) tmpV2[1]: "<<tmpV2[1]<<endl
valuecout<<"B) tmpV2[1]: "<<vec[1] <<endl
both will show same result
What you have done so far is
You have a vector of integer pointers
You have initialized this array
You had one temporary pointer pointing to the zeroth index of the vector
Now using this pointer you printed the value pointed by the second index of the vec
After that you manipulated all the values pointed by vector of pointers (incremented by 4)
Now you are again printing the value pointed by index 1 of vector
Both are same only thing is you printed the value manipulated it and again printed after manipulation. If you reprint both *vec[1] and tmpV2[1] at the end again you will find both are same.

pointer & array conflict

let
int*p ,b = 5;
p = &b;
denotes a ONE DIMENSIONAL array, then what is the output given by following statement
printf("%d",p);
is it an address? if it is an address then tell me which element it belongs,please explain clearly
p = &b
This doesn't denote an array! As I explained here, they're not the same thing. b is just an integer value. If you declare b as int b[] = {1, 2, 3}; then p will point to b's first element.
printf("%d",p);
This will print p's value, and since p is a pointer and points to b, this will print b's address. printf("%d", &b); will give the same result.
By the way, if b was an array, b[5] would be translated into *(p + 5), so you can read (and write) values by adding the number of elements to the beginning of the array. And b[5] == p[5] == *(b + 5) == *(p + 5)!!! But not because arrays and pointers are the same thing, just because an array's name translates to its first element's address.
As a side note, compilers always use pointers notation (*(base + offset)) when compiling to assembly.
The p pointer does not denote a one-dimensional array. It is simply a pointer to an integer. It may point to the first element of an array, like when you do int* p = new int[6], but that's something entirely different; in that case you allocate space for a new array of six integers and you store the address of the first one (or, the beginning of the array) in p.
If you print p it will print the memory address it stores. If p "denotes an array" (emphasis on quotes) then you will print the address of the first element of the array.
int*p ,b = 5;
p = &b;
is exactly equivalent to:
int b = 5;
int *p = &b;
p ends up being a pointer to int. Now its true that this code will have much the same effect on what ends up in p (although b has a completely different type and value) as this:
int b[1] = {5};
int *p = b; // or int *p = &b[0];
certainly in either case p points to an int which you may treat as a simple int, or as the first (and only) element in a one-dimensional array of size one. So, what follows is legal and gives meaningful results in both cases:
printf("%d is stored at %p\n", *p, p);
printf("%d\n",p[0]);
but that's pretty much where the similarity ends.
address of the first element of the array. (if b was an array)
use p++ to scroll through the array

iterative version of easy recursive algorithm

I have a quite simple question, I think.
I've got this problem, which can be solved very easily with a recursive function, but which I wasn't able to solve iteratively.
Suppose you have any boolean matrix, like:
M:
111011111110
110111111100
001111111101
100111111101
110011111001
111111110011
111111100111
111110001111
I know this is not an ordinary boolean matrix, but it is useful for my example.
You can note there is sort of zero-paths in there...
I want to make a function that receives this matrix and a point where a zero is stored and that transforms every zero in the same area into a 2 (suppose the matrix can store any integer even it is initially boolean)
(just like when you paint a zone in Paint or any image editor)
suppose I call the function with this matrix M and the coordinate of the upper right corner zero, the result would be:
111011111112
110111111122
001111111121
100111111121
110011111221
111111112211
111111122111
111112221111
well, my question is how to do this iteratively...
hope I didn't mess it up too much
Thanks in advance!
Manuel
ps: I'd appreciate if you could show the function in C, S, python, or pseudo-code, please :D
There is a standard technique for converting particular types of recursive algorithms into iterative ones. It is called tail-recursion.
The recursive version of this code would look like (pseudo code - without bounds checking):
paint(cells, i, j) {
if(cells[i][j] == 0) {
cells[i][j] = 2;
paint(cells, i+1, j);
paint(cells, i-1, j);
paint(cells, i, j+1);
paint(cells, i, j-1);
}
}
This is not simple tail recursive (more than one recursive call) so you have to add some sort of stack structure to handle the intermediate memory. One version would look like this (pseudo code, java-esque, again, no bounds checking):
paint(cells, i, j) {
Stack todo = new Stack();
todo.push((i,j))
while(!todo.isEmpty()) {
(r, c) = todo.pop();
if(cells[r][c] == 0) {
cells[r][c] = 2;
todo.push((r+1, c));
todo.push((r-1, c));
todo.push((r, c+1));
todo.push((r, c-1));
}
}
}
Pseudo-code:
Input: Startpoint (x,y), Array[w][h], Fillcolor f
Array[x][y] = f
bool hasChanged = false;
repeat
for every Array[x][y] with value f:
check if the surrounding pixels are 0, if so:
Change them from 0 to f
hasChanged = true
until (not hasChanged)
For this I would use a Stack ou Queue object. This is my pseudo-code (python-like):
stack.push(p0)
while stack.size() > 0:
p = stack.pop()
matrix[p] = 2
for each point in Arround(p):
if matrix[point]==0:
stack.push(point)
The easiest way to convert a recursive function into an iterative function is to utilize the stack data structure to store the data instead of storing it on the call stack by calling recursively.
Pseudo code:
var s = new Stack();
s.Push( /*upper right point*/ );
while not s.Empty:
var p = s.Pop()
m[ p.x ][ p.y ] = 2
s.Push ( /*all surrounding 0 pixels*/ )
Not all recursive algorithms can be translated to an iterative algorithm. Normally only linear algorithms with a single branch can. This means that tree algorithm which have two or more branches and 2d algorithms with more paths are extremely hard to transfer into recursive without using a stack (which is basically cheating).
Example:
Recursive:
listsum: N* -> N
listsum(n) ==
if n=[] then 0
else hd n + listsum(tl n)
Iteration:
listsum: N* -> N
listsum(n) ==
res = 0;
forall i in n do
res = res + i
return res
Recursion:
treesum: Tree -> N
treesum(t) ==
if t=nil then 0
else let (left, node, right) = t in
treesum(left) + node + treesum(right)
Partial iteration (try):
treesum: Tree -> N
treesum(t) ==
res = 0
while t<>nil
let (left, node, right) = t in
res = res + node + treesum(right)
t = left
return res
As you see, there are two paths (left and right). It is possible to turn one of these paths into iteration, but to translate the other into iteration you need to preserve the state which can be done using a stack:
Iteration (with stack):
treesum: Tree -> N
treesum(t) ==
res = 0
stack.push(t)
while not stack.isempty()
t = stack.pop()
while t<>nil
let (left, node, right) = t in
stack.pop(right)
res = res + node + treesum(right)
t = left
return res
This works, but a recursive algorithm is much easier to understand.
If doing it iteratively is more important than performance, I would use the following algorithm:
Set the initial 2
Scan the matrix for finding a 0 near a 2
If such a 0 is found, change it to 2 and restart the scan in step 2.
This is easy to understand and needs no stack, but is very time consuming.
A simple way to do this iteratively is using a queue.
insert starting point into queue
get first element from queue
set to 2
put all neighbors that are still 0 into queue
if queue is not empty jump to 2.

Resources