how do I properly re-prompt a statement in mario.c? - cs50

im having problems with my code. at first, it would reject the answer inputted and stopped the code. but as soon as I added a return function. the code would abruptly end. what should I do?
here is my code. it's in C
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int height;
do
{
height = get_int("pick a number, any number!: ");
}
while ( height < 1 && height > 8);
// here is my problem
return (-3);
if ( height > 0 && height < 9)
{
int counter = 0;
for ( int row = 0; row < height; row++)
{
if ( counter != height)
{
for ( int spaces = (height - 1) - counter; spaces > 0; spaces--)
{
printf (" ");
}
for ( int hashes = 0; hashes <= counter; hashes++)
{
printf ("#");
}
printf(" ");
for ( int hashes = 0; hashes <= counter; hashes++)
{
printf ("#");
}
printf ("\n");
counter++;
}
}
}
}
P.S. I'm kinda new to this

You have a mistake in your do-while loop. You should say
while (height < 1 || height > 8)
Your current code says
while (height < 1 && height > 8)
which makes no sense because the height can never be both smaller than 1 and greater than 8.

Related

Add anti-aliasing/bandlimit for looped wav sample (NOT Fourier transform)

How to build antialiasing interpolation using c++ code? I have a simple 4096 or 1024 buffer. Of course when I play this at high frequencies I get aliasing issues. to avoid this, the signal must be limited by the bandwidth at high frequencies. Roughly speaking, the 'sawtooth' wave at high frequencies should looks like a regular sine. And that is what I want to get so that my sound didn't sound dirty like you moving knobs in your old FM/AM radio in your car.
I know how to build bandlimited square,triangle,sawtoth with Fourier transform. So my question is only about wavetable
Found solution in the AudioKit sources. One buffer will be split into 10 buffers/octaves. So when you play a sound, you don't play your original wave, but play a sample that was prepared for a specific octave.
Import to your project WaveStack.hpp
namespace AudioKitCore
{
// WaveStack represents a series of progressively lower-resolution sampled versions of a
// waveform. Client code supplies the initial waveform, at a resolution of 1024 samples,
// equivalent to 43.6 Hz at 44.1K samples/sec (about 23.44 cents below F1, midi note 29),
// and then calls initStack() to create the filtered higher-octave versions.
// This provides a basis for anti-aliased oscillators; see class WaveStackOscillator.
struct WaveStack
{
// Highest-resolution rep uses 2^maxBits samples
static constexpr int maxBits = 10; // 1024
// maxBits also defines the number of octave levels; highest level has just 2 samples
float *pData[maxBits];
WaveStack();
~WaveStack();
// Fill pWaveData with 1024 samples, then call this
void initStack(float *pWaveData, int maxHarmonic=512);
void init();
void deinit();
float interp(int octave, float phase);
};
}
WaveStack.cpp
#include "WaveStack.hpp"
#include "kiss_fftr.h"
namespace AudioKitCore
{
WaveStack::WaveStack()
{
int length = 1 << maxBits; // length of level-0 data
pData[0] = new float[2 * length]; // 2x is enough for all levels
for (int i=1; i<maxBits; i++)
{
pData[i] = pData[i - 1] + length;
length >>= 1;
}
}
WaveStack::~WaveStack()
{
delete[] pData[0];
}
void WaveStack::initStack(float *pWaveData, int maxHarmonic)
{
// setup
int fftLength = 1 << maxBits;
float *buf = new float[fftLength];
kiss_fftr_cfg fwd = kiss_fftr_alloc(fftLength, 0, 0, 0);
kiss_fftr_cfg inv = kiss_fftr_alloc(fftLength, 1, 0, 0);
// copy supplied wave data for octave 0
for (int i=0; i < fftLength; i++) pData[0][i] = pWaveData[i];
// perform initial forward FFT to get spectrum
kiss_fft_cpx spectrum[fftLength / 2 + 1];
kiss_fftr(fwd, pData[0], spectrum);
float scaleFactor = 1.0f / (fftLength / 2);
for (int octave = (maxHarmonic==512) ? 1 : 0; octave < maxBits; octave++)
{
// zero all harmonic coefficients above new Nyquist limit
int maxHarm = 1 << (maxBits - octave - 1);
if (maxHarm > maxHarmonic) maxHarm = maxHarmonic;
for (int h=maxHarm; h <= fftLength/2; h++)
{
spectrum[h].r = 0.0f;
spectrum[h].i = 0.0f;
}
// perform inverse FFT to get filtered waveform
kiss_fftri(inv, spectrum, buf);
// resample filtered waveform
int skip = 1 << octave;
float *pOut = pData[octave];
for (int i=0; i < fftLength; i += skip) *pOut++ = scaleFactor * buf[i];
}
// teardown
kiss_fftr_free(inv);
kiss_fftr_free(fwd);
delete[] buf;
}
void WaveStack::init()
{
}
void WaveStack::deinit()
{
}
float WaveStack::interp(int octave, float phase)
{
while (phase < 0) phase += 1.0;
while (phase >= 1.0) phase -= 1.0f;
int nTableSize = 1 << (maxBits - octave);
float readIndex = phase * nTableSize;
int ri = int(readIndex);
float f = readIndex - ri;
int rj = ri + 1; if (rj >= nTableSize) rj -= nTableSize;
float *pWaveTable = pData[octave];
float si = pWaveTable[ri];
float sj = pWaveTable[rj];
return (float)((1.0 - f) * si + f * sj);
}
}
Then use it in this way:
//wave and outputWave should be float[1024];
void getSample(int octave, float* wave, float* outputWave){
uint_fast32_t impulseCount = 1024;
if (octave == 0){
impulseCount = 737;
}else if (octave == 1){
impulseCount = 369;
}
else if (octave == 2){
impulseCount = 185;
}
else if (octave == 3){
impulseCount = 93;
}
else if (octave == 4){
impulseCount = 47;
}
else if (octave == 5){
impulseCount = 24;
}
else if (octave == 6){
impulseCount = 12;
}
else if (octave == 7){
impulseCount = 6;
}
else if (octave == 8){
impulseCount = 3;
}
else if (octave == 9){
impulseCount = 2;
}
//Get sample for octave
stack->initStack(wave, impulseCount);
for (int i = 0; i < 1024;i++){
float phase = (1.0/float(1024))*i;
//get interpolated wave and apply volume compensation
outputWave[i] = stack->interp(0, phase) / 2.0;
}
}
Then... when 10 buffers is ready. You can use them when playing a sound. Using this code you can get index of buffer/octave depending to your frequency
uint_fast8_t getBufferIndex(const float& frequency){
if (frequency >= 0 && frequency < 40){
return 0;
}
else if (frequency >= 40 && frequency < 80){
return 1;
}else if (frequency >= 80 && frequency < 160){
return 2;
}else if (frequency >= 160 && frequency < 320){
return 3;
}else if (frequency >= 320 && frequency < 640){
return 4;
}else if (frequency >= 640 && frequency < 1280){
return 5;
}else if (frequency >= 1280 && frequency < 2560){
return 6;
}else if (frequency >= 2560 && frequency < 5120){
return 7;
}else if (frequency >= 5120 && frequency < 10240){
return 8;
}else if (frequency >= 10240){
return 9;
}
return 0;
}
So if I know that my note frequency 440hz. Then for this note I'm getting wave in this way:
float notInterpolatedSound[1024];
float interpolatedSound[1024];
uint_fast8_t octaveIndex = getBufferIndex(440.0);
getSample(octaveIndex, notInterpolatedSound, interpolatedSound);
//tada!
ps. the code above is a low pass filter. I also tried to do sinc interpolation. But sinc worked for me very expensive and not exactly. Although maybe I did it wrong.

CS50 pset 1 - Credit, more comfortable

I have the following errors
:( identifies 5105105105105100 as MASTERCARD
expected "MASTERCARD\n", not "INVALID\n"
:( identifies 4111111111111111 as VISA
expected "VISA\n", not "INVALID\n"
:( identifies 4012888888881881 as VISA
expected "VISA\n", not "INVALID\n"
but for the card to be correct the last digit should be which is correct in my case. Please help
------------------- CODE -----------------------
#include <cs50.h>
#include <stdio.h>
int main()
{
long long cardNumber;
// get a card number from the user
do
{
printf("Your card number please: ");
//scanf("%lld", &cardNumber);
cardNumber = get_long_long();
}
while (cardNumber < 0);
//check the length of the card
int counter = 0;
long long cardNumberNeo = cardNumber;
while (cardNumberNeo > 0)
{
cardNumberNeo = cardNumberNeo / 10;
counter++;
}
if (counter != 15 && counter != 16 && counter != 13)
{
printf("INVALID\n");
}
// Array of card number
cardNumberNeo = cardNumber;
int cardNumberArr[counter], cardNumberArrNeo[counter], i;
for (i=0; i<counter; i++)
{
cardNumberArr[counter-i-1] = cardNumberNeo % 10;
cardNumberArrNeo[counter-i-1] = cardNumberArr[counter-i-1];
cardNumberNeo = cardNumberNeo / 10;
}
for (int i = 1; i < counter; i+=2)
{
cardNumberArrNeo[i] = cardNumberArrNeo[i] * 2;
}
int oddNumber = 0;
int temp;
for (int i = 0; i < counter; i++)
{
temp = (cardNumberArrNeo[i] % 10) + (cardNumberArrNeo[i]/10 % 10);
oddNumber = oddNumber + temp;
}
if (oddNumber % 10 == 0)
{
// Check the type of the card
if ( ((cardNumberArr[0] == 3 && cardNumberArr[1] == 4) || (cardNumberArr[0] == 3 && cardNumberArr[1] == 7)) && counter == 15 )
{
printf("AMEX\n");
}
else if (cardNumberArr[0] == 5 && cardNumberArr[1] >= 1 && cardNumberArr[1] <= 5 && counter == 16)
{
printf("MASTERCARD\n");
}
else if (cardNumberArr[0] == 4 && (counter == 13 || counter == 16 ))
{
printf("VISA\n");
}
else
{
printf("INVALID\n");
}
}
else
{
printf("INVALID\n");
}
return 0;
}
This will work.....as long as the credit card number has an odd length. Remember, Luhn's algorithm rule [emphasis added]:
Multiply every other digit by 2, starting with the number’s
second-to-last digit, and then add those products' digits together.
This loop for (int i = 1; i < counter; i+=2) processes the wrong digits for a card with even length. Such numbers need to start at the 0th index in order to end up at the correct place (ie penultimate digit).

Stack around the variable A (array) or n (size of the array) was corrupted

This program checks distinctness in an array. (no repeated values in an array I.e if 1 2 3 3 4 is an array it is not distinct). this code Won't compile although (I believe that) index of array did not go out of range in for loop.
theRun-Time Check Failure says stack around variable 'n' was corrupted when I enter n =12. BUT says stack around variable 'A' was corrupted when I enter n = 10. with exactly the same variables entered in the array in the second step. (the error shows up after entering the fourth integer)
#include <iostream>
using namespace std;
int main()
{
int n;
int A[] = {0};
int integer;
cout<<"Enter the size of the array\n";
cin>>n;
cout<<"enter "<<n<<" integers\n";
for (int i = 0 ; i < n ; i++)
{
cin>>A[i];
}
for (int i = 0 ; i < n ; i++)
{
for (int j = 0 ; j < n - i; j++)
{
if(A[j+1] > A[j])
{
int temp;
temp = A[j];
A[j+1] = A[j];
A[j+1] = temp;
}
}
}
for (int i = 0 ; i < n; i++)
{
if (A[i] - A[i+1] ==0 ){
cout<<"\nThe Array Is Not Distinct !\n";
break;
}
else
{
cout<<"\nThe Array Is Distinct !\n";
}
}
system("pause");
return 0;
}

DP Approach ? Output should be the max sum. interview ( still have not idea, any hints) at at well known company

You have a table and in each cell there is either a positive integer or the cell is blocked. You have a player starting from bottom left and want to get to the top right in such a way that you maximize the sum of integers on your way. You are only allowed to move up or right but not through blocked cells. Output should be the max sum.
On my code I am making the assumption that the answer will fit on a long long type.
I am also assuming that is a square matrix for simplicity, but you can adapt the algorithm for any rectangular matrix with almost no effort.
If the input matrix is N x N, the complexity of this approach is O(N ^ 2).
#include <vector>
#include <iostream>
#include <algorithm>
constexpr int maxDimension = 100;
using namespace std;
long long matrix[maxDimension][maxDimension];
long long dp[maxDimension][maxDimension];
int main()
{
// I am assuming that the matrix is filled with positive
// integers, and the blocked cell's are filled with -1.
// reading the values for the matrix
for(int i = 0; i < maxDimension; ++i)
{
for(int j = 0; j < maxDimension; ++j)
{
cin >> matrix[i][j];
}
}
/*
For every pair(i, j),
dp[i][j] is the maximum
sum we can achive going from
(0,0) to (i, j)
*/
// Observation if dp[i][j] is equal to -1, it is because we cannot reach the cell (i, j) because of blocked cells
dp[0][0] = matrix[0][0];
// this calculates the dp for row == 0
for(int col = 1; col < maxDimension; ++col)
{
if(dp[0][col - 1] != -1 && matrix[0][col] != -1)
{
dp[0][col] = dp[0][col-1] + matrix[0][col];
}
else dp[0][col] = -1;
}
// now I will calculate the dp for column == 0
for(int row = 1; row < maxDimension; ++row)
{
if(dp[row - 1][0] != -1 && matrix[row][0] != -1)
{
dp[row][0] = dp[row-1][0] + matrix[row][0];
}
else dp[row][0] = -1;
}
// Now that I have calculated the base cases, I will calculate the dp for the other states
// I will use the following expression
/* dp[i][j] = if (matrix[i][j] == -1) -> -1
else if (dp[i-1][j] != -1 or dp[i][j-1] != -1) -> max(dp[i-1][j], dp[i][j - 1]) + matrix[i][j]
else -> -1
*/
for(int row = 1; row < maxDimension; ++row)
{
for(int col = 1; col < maxDimension; ++col)
{
if(matrix[i][j] != -1 && ( dp[i-1][j] != -1 || dp[i][j-1] != -1) )
{
dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + matrix[i][j];
}
else dp[i][j] = -1;
}
}
if(dp[maxDimension-1][maxDimension-1] == -1) cout << "The top right cell is not reachable from the bottom left cell" << endl;
else cout << "The best sum possible is " << dp[maxDimension - 1][maxDimension - 1] << endl;
return 0;
}

Why is this triggering a breakpoint?

I have looked extensively for the problem in this code, but I can't seem to figure out what tragic error I made and why it is triggering a breakpoint.
(After 3 or 4 inputs, it triggers and I don't know why it doesn't trigger at the start or what is causing it)
#include <conio.h> // For function getch()
#include <cstdlib> // For several general-purpose functions
#include <fstream> // For file handling
#include <iomanip> // For formatted output
#include <iostream> // For cin, cout, and system
#include <string> // For string data type
using namespace std; // So "std::cout" may be abbreviated to "cout", for example.
string convertDecToBin(int dec)
{
int *arrayHex, arraySize = 0;
arrayHex = new int[];
string s = " ";
int r = dec;
for (int i = 0; r != 0; i++)
{
arrayHex[i] = r % 2;
r = r / 2;
arraySize++;
}
for (int j = 0; j < arraySize; j++)
{
s = s + to_string(arrayHex[arraySize - 1 - j]);
}
delete[] arrayHex;
return s;
}
string convertDecToOct(int dec)
{
int *arrayHex, arraySize = 0;
arrayHex = new int[];
string s = " ";
int r = dec;
for (int i = 0; r != 0; i++)
{
arrayHex[i] = r % 8;
r = r / 8;
arraySize++;
}
for (int j = 0; j < arraySize; j++)
{
s = s + to_string(arrayHex[arraySize - 1 - j]);
}
delete[] arrayHex;
return s;
}
int main()
{
int input = 0;
while (input != -1)
{
cout << "\nEnter a decimal number (-1 to exit loop): ";
cin >> input;
if (input != -1)
{
cout << "Your decimal number in binary expansion: " << convertDecToBin(input);
cout << "\nYour decimal number in octal ecpression: " << convertDecToOct(input);
}
}
cout << "\n\nPress any key to exit. . .";
_getch();
return 0;
}
arrayHex = new int[] is your problem - C\C++ does not support dynamic sizing arrays. You need to specify a size for the array to allocation, otherwise you'll get memory block overruns.

Resources