I have 2 txt files where I have numbers > 0 and I have to combine and sort them. Also there cannot be 2 same values.
Here are values of files.
File1:
1
2
3
4
5
6
7
File2:
1
3
6
8
10
The output should look like this:
1
2
3
4
5
6
7
8
10
The code which I have so far:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fr1,*fr2;
int fst, snd, p[256], i=0, n=0;
bool f1=true,f2=true;
fr1 = fopen("txt/cisla.txt","r");
fr2 = fopen("txt/cisla2.txt","r");
while(feof(fr1) == 0 && feof(fr2) == 0)
{
if (f1) fscanf(fr1, "%d", &fst);
if (f2) fscanf(fr2, "%d", &snd);
printf("%d - %d\n", fst, snd);
if (fst == snd)
{
f1 = true;
f2 = true;
p[i] = fst;
} else if (fst > snd)
{
p[i] = snd;
f1 = false;
f2 = true;
} else
{
f2 = false;
f1 = true;
p[i] = fst;
}
i++;
}
fclose(fr1);
fclose(fr2);
printf("\n\n\n");
for(int j = 0; j < i; j++)
{
printf("%d\n", p[j]);
}
return 0;
}
The result of this is:
1 - 1
2 - 3
3 - 3
4 - 6
5 - 6
6 - 6
7 - 8
1
2
3
4
5
6
7
The bottom part is the array. At top I am writing the values which are read. The thing is it seems to stop at the end of the first file but I want it to continue the second one even if the first one is at the end
The thing is it seems to stop at the end of the first file
That's because you told it to do so - the continuation condition that you have is that both feofs returned zero:
while(feof(fr1) == 0 && feof(fr2) == 0) {
...
}
I want it to continue the second one even if the first one is at the end
Add two more loops after the first one, to write out the "tail" of the file with the larger elements:
while(feof(fr1) == 0 && feof(fr2) == 0) {
... // Do the merge
}
while(feof(fr1) == 0) {
... // Read from fr1, and write to the output
}
while(feof(fr2) == 0) {
... // Read from fr2, and write to the output
}
Your while loop says to continue while BOTH files are not at the end; I think you want it to continue as long as EITHER is not at the end. Of course, you'd better be sure not to try and read from the one that IS at the end...
This small improvement could be of help.
while(feof(fr1) == 0 || feof(fr2) == 0)
{}
This is because you want to loop or read untill both the files are not completely read.
Btw, why can't you use some generic container..
Your question is tagged as C++, but the code presented doesn't look like it. It looks more like C.
It's much easier to accomplish what you're trying to do if you avoid reinventing the wheel and use the C++ standard library.
Here's a simple example of how to do it using std::vector and the standard library:
// Open file streams for reading.
std::ifstream fr1{"file1.txt"};
std::ifstream fr2{"file2.txt"};
// Read number tokens into a std::vector from both files.
std::vector<int> v{std::istream_iterator<int>{fr1}, std::istream_iterator<int>{}};
v.insert(std::begin(v), std::istream_iterator<int>{fr2}, std::istream_iterator<int>{});
// Sort the vector.
std::sort(std::begin(v), std::end(v));
// Remove consecutive duplicates (move them to back of vector).
auto end = std::unique(std::begin(v), std::end(v));
// Remove duplicate elements.
if (end != std::end(v)) {
v.erase(end, std::end(v));
}
// Output vector.
for (int i : v) {
std::cout << i << std::endl;
}
Look at this live example
Related
So I need to make a program that lists all permutations.
There are 4 characters:
"1",
"2",
"R",
"T"
The conditions is that the "R" needs to have "1" before and after him so it sits like this 1-R-1
The "T" condition is that either "1" or "2" are after him so it sits like this T-1 or T-2
The max length should be 10
The output should be like this:
111
112
121
122
1R1
1T1
1T2
211
212
221
222
2T1
2T2
T11
T12
T21
T22
I have managed to figure out the permutations part but I just cannot make them work with the conditions
void displayPermutation(string permutation[], int length){
int i;
for (i=0;i<length;i++){
cout<<permutation[i];
}
cout << endl;
}
void getPermutations(string operatorBank[], int operatorCount,
string permutation[],int permutationLength, int curIndex){
int i;
//stop recursion condition
if(curIndex == permutationLength){
displayPermutation(permutation,permutationLength);
}
else{
for(i = 0; i < operatorCount; i++){
permutation[curIndex] = operatorBank[i];
getPermutations(operatorBank,operatorCount,permutation,
permutationLength,curIndex+1);
}
}
}
int main ()
{
int operatorCount = 4;
int permutationLength = 3;
string operatorBank[] = {"1","2","R","T"};
string permutation[] = {"","","",""}; //empty string
int curIndex = 0;
getPermutations(operatorBank,operatorCount,permutation,
permutationLength,curIndex);
return 0;
}
You got your terms a little mixed up. You're not talking about permutations[1] but about combinations[2].
As far as I can tell you already have the algorithm (recursive backtracking) you're just not checking if your solution is valid, by filtering the solution space. So you're generating all solutions without taking into account any constraint and you print a solution when you reached the permutationLength. At this step you can also check if the solution is valid by checking if it abides by the conditions. If it is you print it, if not you discard it.
Strategy for this would be:
Look for R and check if permutation[idx-1] is 1 and permutation[idx+1] is 1
Look for T and check if permutation[idx+1] is either 1 or 2.
You only print the solution if these conditions are met!
...
if(curIndex == permutationLength){
if (solutionValid()) {
displayPermutation(permutation,permutationLength);
}
}
...
https://mathworld.wolfram.com/Permutation.html
https://mathworld.wolfram.com/Combination.html
Do you mean a recursion like this?
function f(n, str=""){
if (!n)
return [str];
let result = [];
if (n >= 3)
result = result.concat(f(n - 3, str + "1R1"));
if (n >= 2)
result = result
.concat(f(n - 2, str + "T1"))
.concat(f(n - 2, str + "T2"));
return result
.concat(f(n - 1, str + "1"))
.concat(f(n - 1, str + "2"));
}
console.log(f(3));
I was solving this Question:
A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs.
I tried to solve this using this :
#include <iostream>
using namespace std;
int ways(int N){
if(N == 1 || N == 2) {
return N;
}else if(N <= 0) {
return 0;
}
return ways(N-1)+ways(N-2)+ways(N-3);
}
int main() {
cout<<ways(4);
return 0;
}
Output : 4
Expected Output : 7
I am taking f(0<=N) = 0, f(1) = 1 and f(2) = 2, where f(x) is number of ways to climb xth Stair.
But, it is giving wrong output. I then looked at the solution at observed that f(0) = 1 was also considered, which according to me should be f(0) = 0 as there are no ways to climb 0th Stair.
change following:
if(N == 1 || N == 0) {
return 1;
} else if(N == 2) {
return 2;
}
Consider scenario when three steps are there. last return will execute
ways(n-1) + ways(n-2) + ways(n-3)
which means
ways(2) + ways(1) + ways(0)
Here third part represents how many ways can child climb using 3 stairs at time. That would be returned as 0 but that should be 1. He can climb three stairs in using 3 steps in 1 way
Look at the following 2 examples. How to make sure the 2nd one prints 4 as well?
String s="a|b|c|d"
println(s.split("\\|").length)
//prints 4
s="a|b||"
println(s.split("\\|").length)
//prints 2
To keep the empty token, use split with limit = -1
println(s.split("\\|", -1).length)
Split wont allow you to have null values when you iterate. So the following code will work.
int counter = 0;
for(int i = 0 ; i < s.length();i++)
{
if(s.charAt(i) == '|')
{
counter++;
}
}
System.out.println(counter);
So I'm having a lot of trouble understanding c++ again I've taken my programming class twice and failed. I need help. I'm not interested in programming anymore because it's obviously not for me. I just need to pass. Here's the problem:
The goal of this assignment is to practice recursive algorithms by writing a program that takes in a matrix representing the number of guards in each room of the castle and outputs the fastest path to the princess and the number of guards you will have to fight.
You're moving through a map(array) that looks like:
5 5
6 2 3 44 15
1 7 2 9 10
11 1 5 14 12
5 17 2 1 20
21 7 33 4 25
Where the first to numbers are the size of your array and you can only move right and down.
So an output would be:
50 > > v v v > v >
We're given a skeleton which we have to fill in but I don't know what some of it does and it might be too long to copy and paste here, I'm new to the community.
How would you tackle this assignment
Using recursion you try to simplify the problem. So take a step right, compute the score for this step and add it to the rest of the solution by calling the same function on a smaller matrix (leaving out the left column). Then take a step down and do the same with the smaller matrix leaving out the top row. Then choose the solution with the lowest score.
This is just a dynamic programming problem.
I don't know how to pass a 2-d array as a function parameter.
Someone correct me please(How to pass 'matrix' array and 'result' array as function parameters). Rest all part is fine
Algorithm is simple. Just start from the last position and come backwards.
where result[i][j] = min(result[i+1][j],result[i][j+1])
void function(int a,int b,int** matrix,int** result){
if(result[a+1][b] == -1 && result[a][b+1] == -1){
result[a][b] = min(function(a+1,b,matrix,result),function(a,b+1,matrix,result));
}
else if(result[a+1][b] == -1 && result[a][b+1] != -1){
result[a][b] = min(function(a+1,b,matrix,result),result[a][b+1]);
}
else if(result[a+1][b] != -1 && result[a][b+1] == -1){
result[a][b] = min(result[a+1][b],function(a,b+1,matrix,result));
}
return;
}
int main(){
int p,q;
cin>>p>>q;
int matrix[p][q];
for(int i=0;i<p;i++){
for(int j=0;j<q;j++){
cin>>matrix[i][j];
}
}
int result[p][q];
for(int i=0;i<p;i++){
for(int j=0;j<q;j++){
result[i][j] = -1;
}
}
result[p-1][q-1] = matrix[p-1][q-1];
for(int i=q-2;i>=0;i++){
result[p-1][i] = matrix[p-1][i] + result[p-1][i+1];
}
for(int i=p-2;i>=0;i++){
result[i][q-1] = matrix[i][q-1] + result[i+1][q-1];
}
function(0,0,matrix,result);
cout<<results[0][0]<<endl;
}
I am trying to implement Long Hand Multiplication method for 8 bit binary numbers stored in two arrays BeforeDecimal1 and BeforeDecimal2. The problem is I always get the wrong result. I tried to figure out the issue but couldn't do it. Here is the code:
This is a much more refined code then previous one. It is giving me result but the result is not correct.
int i=0,carry=0;
while(true)
{
if(BeforeDecimal2[i]!=0)
for(int j=7;j>=0;j--)
{
if(s[j]==1 && BeforeDecimal1[j]==1 && carry==0)
{
cout<<"Inside first, j= "<<j<<endl;
carry=1;
s[j]=0;
}
else
if(s[j]==1 && BeforeDecimal1[j]==0 && carry==1)
{
cout<<"Inside second, j= "<<j<<endl;
carry=1;
s[j]=0;
}
else
if(s[j]==0 && BeforeDecimal1[j]==0 && carry==1)
{
cout<<"Inside third, j= "<<j<<endl;
carry=0;
s[j]=1;
}
else
if(s[j]==0 && BeforeDecimal1[j]==0 && carry==0)
{
cout<<"Inside fourth, j= "<<j<<endl;
carry=0;
s[j]=0;
}
else
if(s[j]==0 && BeforeDecimal1[j]==1 && carry==0)
{
cout<<"Inside fifth, j= "<<j<<endl;
carry=0;
s[j]=1;
}
else
if(s[j]==1 && BeforeDecimal1[j]==1 && carry==1)
{
//cout<<"Inside fifth, j= "<<j<<endl;
carry=1;
s[j]=1;
}
else
if(s[j]==1 && BeforeDecimal1[j]==0 && carry==0)
{
//cout<<"Inside fifth, j= "<<j<<endl;
carry=0;
s[j]=1;
}
else
if(s[j]==0 && BeforeDecimal1[j]==1 && carry==1)
{
//cout<<"Inside fifth, j= "<<j<<endl;
carry=1;
s[j]=0;
}
}
for(int h=7;h>=0;h--)
{
if(h==0)
{
BeforeDecimal1[0]=0; // that is inserting zeros from the right
}
else
{
BeforeDecimal1[h]=BeforeDecimal1[h-1];
BeforeDecimal1[h-1]=0;
}
}
if(i==3)
break;
i++;
}
Regards
Maybe it would be easiest to back up and start with 8-bit binary numbers stored as 8-bit binary numbers. Much like when we do decimal multiplication, we start with a number of digits. We take the values of multiplying by those individual digits, and add them together to get the final result. The difference (or one obvious difference) is this since we're working in binary, all our digits represent powers of two, so we can get each intermediate result by simply bit shifting the input.
Since it's binary, we have only two possibilities for each digit: if it's a 0, then we need to add 0 times the other number shifted left the appropriate number of places. Obviously, 0 time whatever is still 0, so we simply do nothing in this case. The other possibility is that we have a 1, in which case we add 1 times the other number shifted left the appropriate number of places.
For example, let's consider something like 17 x 5, or (in binary) 10001 x 101.
10001
101
------
10001
+ 1000100
--------
= 1010101
Converting that to something more recognizable, we get 0x55, or 85d.
In code, that process comes out fairly short and simple. Start with a result of 0. Check whether the least significant bit in one operand is set. If so, add the other operand to the result. Shift the one operand right a bit and the other left a bit, and repeat until the operand you're shifting to the right equals 0:
unsigned short mul(unsigned char input1, unsigned char input2) {
unsigned short result = 0;
while (input2 != 0) {
if (input2 & 1)
result += input1;
input1 <<= 1;
input2 >>= 1;
}
return result;
}
If you want to deal with signed numbers, it's generally easiest to figure up the sign of the result separately, and do the multiplication on the absolute values.
You have problem in following lines of code
if(reverse==0)
{
totalReverse=totalReverse-1;
reverse=totalReverse;
}
after some iterations of the inner for loop (index j based) the values of reverse goes should goes to negative and when reverse less than 3 then there should be exception thrown.
Are you running this code without exception handling?
to me this smells like shift and add. is there a requirement that you may use operations simulating logical gates only?
for your full adder you have 3 inputs s(s[j]), b(BeforeDecimal1[j]), c(carry), and two outputs ns(new s[j]), nc (new carry)
the table looks like this
s b c ns nc
0 0 0 0 0 handled in v5 clause 4
0 0 1 1 0 handled in v5 clause 3
0 1 0 1 0 handled in v6 clause 5
0 1 1 0 1
1 0 0 1 0
1 0 1 0 1 handled in v5 clause 2
1 1 0 0 1 handled in v5 clause 1
1 1 1 1 1
your code covers only 4 (now 5) of these 8 clauses
to avoid the ugly if-else-if rake i recommend to use temporary result variables (carry and s still valid in the next if clause)
when you analyze the table you could also do (pseudo bool notation)
nc = s && b || s && c || b && c;
ns = s XOR b XOR c; // there is no XOR in C++: axb = a&&!b || !a&&b
arithmetic notation
nc = (s + b + c) / 2;
ns = (s + b + c) % 2;
// [...]
for(int j=7;j>=0;j--)
{
// start changed code
const int sum = s[j] + BeforeDecimal1[j] + carry;
s[j]=sum % 2;
carry=sum / 2;
// end changed code
}
// [...]
here is a nice simulation of your problem Sequential Multiplication
Unless your requirement precisely states otherwise, which isn't clear from your question or any of your comments so far, it is not necessary to process arrays of bits. Arrays of bytes are much more efficient in both space and time.
You don't need this exhaustive explosion of cases either. The only special case is where either operand is zero, i.e. a[i]|b[i] == 0, when
result[i] = carry;
carry = 0;
All other cases can be handled by:
result[i] = a[i]*b[i]+carry;
carry = (result[i] >>> 8) & 1;
result[i] &= 0xff;
I don't see much point in the names BeforeDecimal1 and BeforeDecimal2 either.