Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
i'm trying to get the smallest and the biggest number possible by rearanging the 3 digit number.
So i success get the biggest
int maxNumFromNum(int num) {
int freq[10] = {0};
string str = to_string(num);
for (int i = 0; i < str.length(); i++)
freq[str[i] - '0']++;
int res = 0, mul = 1;
for (int i = 0; i <= 9; i++) {
while (freq[i] > 0) {
res = res + (i * mul);
freq[i]--;
mul = mul * 10;
}
}
return res;
}
But now i'm trying to get the smallest one. How can be done that.
Example Outpots:
321 Output> 123, 321
598 Output> 985, 598.
And too, is there more efficiency way to do that?
Thanks in advice.
A simple solution:
#include<bits/stdc++.h>
using namespace std;
int main() {
int n = 231;
string s = to_string(n);
sort(s.begin(), s.end());
cout<<"Smaller: "<<s<<endl;
reverse(s.begin(), s.end());
cout<<"Bigger : "<<s<<endl;
}
It works for integers of any size and runs in O(n lg(n)), where n is the number of digits of the integer.
You could simply change the line:
for (int i = 0; i <= 9; i++) {
to
for (int i = 9; i >= 0; i--) {
void getBigAndSmall(string num, string &outBig, string outSmall){
outBig = 0;
outSmall = 0;
//since you're sorting digits you can use this to sort them with O(n)
//this would be faster than std::sort in this case.
int bigArray[10] = {0};
int smallArray[10] = {0};
for (int i = 0; i < 10; i++){
int digit = (int)num[i] - 48; //this might not be good idea.
bigArray[digit]++;
smallArray[digit]++;
}
int digitsSize = num.size();
for (int i = 0; i < digitsSize; i++){
for (int j = 0; j < 10; j++){
if (bigArray[j] > 0){
bigArray[j]--;
outBig += j;
}
}
for (int j = 9; j > -1; j--){
if (smallArray[j] > 0){
smallArray[j]--;
outSmall += j;
}
}
}
}
This might have some mistakes, since I didn't test it, but it has a runtime O(n).
It gives max integer using input digits without using string
int extractMax(int num) {
std::vector<int> digits;
bool flag = false;
int curDigit;
while (num > 0) {
curDigit = num % 10;
num /= 10;
flag = false;
for (int i = 0; i < digits.size(); ++i) {
if (digits[i] > curDigit) {
flag = true;
digits.insert(digits.begin() + i, curDigit);
break;
}
}
if (not flag) digits.push_back(curDigit);
}
std::sort(digits.begin(), digits.end());
int dec = 1, int_val = 0;
for (auto& it : digits){
int_val += it * dec;
dec *= 10;
}
return int_val;
}
If you want to get smallest integer, change this line:
std::sort(digits.begin(), digits.end());
With this:
std::sort(digits.begin(), digits.end(), greater<int>());
Related
int main() {
int naturalNumber = 2;
int divider = 0;
int rest = 1;
long long int sumOfPrimes = 0;
while (naturalNumber <= 2000000) {
divider = naturalNumber;
while (rest != 0) {
divider--;
rest = naturalNumber % divider;
}
rest = 1;
if (divider == 1) {
sumOfPrimes = sumOfPrimes + naturalNumber;
}
naturalNumber++;
}
std::cout << sumOfPrimes;
}
Howcome does the sum output not appear on the Console after I set the loop condition to go through 2million iterations. And I don't get any error message. It works when it's set to less than ~100'000 iterations. Is this a memory issue or something else?
I was trying to calculate a sum of all primenumbers below 2 million through iteration.
This is a very inefficient way to calculate a series of prime numbers, so the most likely answer is that it's just taking a very very long time.
If you know you need all of the primes up to 2,000,000, the Sieve of Eratosthenes is your friend.
Something like:
int n = 2000000;
std::vector<bool> is_prime(n+1, true);
is_prime[0] = is_prime[1] = false;
for (int i = 2; i <= n; i++) {
if (is_prime[i] && (long long)i * i <= n) {
for (int j = i * i; j <= n; j += i)
is_prime[j] = false;
}
}
long long int sum_primes = 0;
for (int i = 0; i < n; i++) {
if (is_prime[i]) sum_primes += i;
}
This runs in O(n) complexity, vs. O(n^2).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I assume that everyone has heard of the game, but if not - here is a link:
https://bitstorm.org/gameoflife/
I'm trying to implement it in C++ without using structs, classes etc.
So far I've done this:
#define N 10
#define M 10
#include <iostream>
bool** createGrid(int n, int m)
{
bool** grid = new bool*[n];
for (int i = 0; i < n; i++)
grid[i] = new bool[m];
return grid;
}
void displayGrid(bool** grid, int n, int m)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 1)
std::cout << 'X';
else
std::cout << '.';
}
std::cout << std::endl;
}
std::cout << "##########\n";
}
void releaseGrid(bool** grid, int n)
{
for (int i = 0; i < n; i++)
delete[] grid[i];
delete[] grid;
}
int countAliveNeighbours(bool** grid, int k, int l)
{
int aliveNeighbours = 0;
for (int i = -1; i <= 1; i++)
for (int j = -1; j <= 1; j++)
aliveNeighbours += grid[k + i][l + j];
// The cell needs to be subtracted from it's neighbours as it was counted before
aliveNeighbours -= grid[k][l];
return aliveNeighbours;
}
bool** nextGeneration(bool** grid, int n, int m)
{
bool** next = createGrid(n, m);
// Loop through every cell
for (int k = 1; k < n - 1; k++) {
for (int l = 1; l < m - 1; l++) {
// finding count of neighbours that are alive
int aliveNeighbours = countAliveNeighbours(grid, k, l);
// Implementing the Rules of Life
// Cell is lonely and dies
if ((grid[k][l] == 1) && (aliveNeighbours < 2))
next[k][l] = 0;
// Cell dies due to over population
else if ((grid[k][l] == 1) && (aliveNeighbours > 3))
next[k][l] = 0;
// A new cell is born
else if ((grid[k][l] == 0) && (aliveNeighbours == 3))
next[k][l] = 1;
// Remains the same
else
next[k][l] = grid[k][l];
}
}
return next;
}
bool checksTwoGridsForDifferences(bool** prevGrid, bool** nextGrid, int n, int m)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (prevGrid[i][j] != nextGrid[i][j]) {
return true;
}
}
}
return false;
}
void fillGrid(bool** grid, int n, int m)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
grid[i][j] = 0;
}
}
grid[1][3] = 1;
grid[1][4] = 1;
grid[2][4] = 1;
grid[5][3] = 1;
grid[5][4] = 1;
grid[6][2] = 1;
grid[6][3] = 1;
grid[7][5] = 1;
grid[8][4] = 1;
}
int main()
{
bool** prevGrid = createGrid(N, M); // create starting grid
fillGrid(prevGrid, N, M); // fill starting grid
std::cout << "Starting grid:\n";
displayGrid(prevGrid, N, M); // display starting grid
bool** nextGrid = nextGeneration(prevGrid, N, M); //generate next grid
while (checksTwoGridsForDifferences(prevGrid, nextGrid, N, M)) {
displayGrid(nextGrid, N, M);
releaseGrid(prevGrid, N);
prevGrid = nextGrid;
nextGrid = nextGeneration(prevGrid, N, M);
}
releaseGrid(nextGrid, N);
releaseGrid(prevGrid, N);
return 0;
}
but I'm stuck, becаuse the third grid is not correct (It wrongly erases two Xs), and I wonder why? Can anyone show me the mistake?
It shows:
..........
..........
...XX.....
..........
...X......
..X.X.....
..........
..XXX.....
..........
..........
instead of:
..........
...XX.....
...XX.....
..........
...X......
..X.X.....
..........
..XXX.....
..........
..........
The problem is that you are not filling in the edges of your next generation grid. The comment // Loop through every cell in nextGeneration is not true because you skip the edges of your grid.
You need to work a bit harder in your countAliveNeighbours function so you don't step over the edge of the grid, and then change your nextGeneration function so that you really do loop through every cell. Or you could have the edges of the grid permanently switched off.
I found this problem in about two minutes using a debugger. I couldn't see it by looking at the code. You really should teach yourself how to use a debugger. It's the biggest step up you'll ever make in your productivity as a programmer.
Well posed question BTW, enough information to easily solve the problem.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
How to dynamically fill the following output in a two-dimensional array with the same number of rows and columns.
Edit: Here is the solution in c++ using #TheGeneral code from c#.
#include <iostream>
using namespace std;
int main(){
int size = 10;
int half = size/2;
int matrix[size][size];
int number1 = 0;
int number2 = 0;
for(int i = 1; i<=size; i++){
for(int j = 1; j<= size; j++){
if(i > half){
number1 = size + 1 - i;
}else{
number1 = i;
}
if(j > half){
number2 = size + 1 - j;
}else{
number2 = j;
}
if(number1 < number2){
matrix[i-1][j-1] = number1;
}else{
matrix[i-1][j-1] = number2;
}
}
}
cout<<"MATRIX:"<<endl;
for(int i=0; i<size; i++){
for(int j=0; j<size; j++){
cout<<"["<<matrix[i][j]<<"] \t";
}
cout<<endl;
}
return 0;
}
For a bit of fun
The only note worthy things going on, are
Starting the index from 1 (makes things easier)
Conditional Operator to say if an index is greater than 5 reverse the count
Math.Min to make it syemtrical
Exmaple
private static int[, ] CreateArray()
{
var ary = new int[10, 10];
for (var i = 1; i <= 10; i++)
for (var j = 1; j <= 10; j++)
ary[i - 1, j - 1] = Math.Min(i > 5 ? 11 - i : i, j > 5 ? 11 - j : j);
return ary;
}
Demo here
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have written a code to find the largest palindrome formed by multiplication of two 3-digit numbers. However instead of just getting the desired answer i.e. the largest palindrome, I am getting the list of all possible palindromes. How do I program it to find the largest.
Code:
#include <iostream>
using namespace std;
int revfunc(int x) {
int rev = 0, num, d;
num = x;
while(num != 0) {
d = num % 10;
rev = (rev * 10) + d;
num = num / 10;
}
long int maxi = 0;
if(x == rev && maxi < x) {
maxi=x;
cout<<maxi<<endl;
}
}
int main() {
long int ans;
for(int i = 100; i <= 999; i++) {
for(int j = 100; j <= 999; j++) {
ans = i * j;
revfunc(ans);
}
}
cin.get();
return 0;
}
In your program you don't actually select the maximum palindrome, you just dump them all. Here is minimal correction for code to work:
bool revfunc(int x){
int rev = 0, num, d;
num = x;
while (num != 0){
d = num % 10;
rev = (rev * 10) + d;
num = num / 10;
}
long int maxi = 0;
return x == rev&&maxi < x;
}
int main()
{
int max_palindrome = 0;
long int ans;
for (int i = 100; i <= 999; i++){
for (int j = 100; j <= 999; j++){
ans = i*j;
if (ans > max_palindrome && revfunc(ans))
{
max_palindrome = ans;
}
}
}
cout << max_palindrome;
cin.get();
return 0;
}
I am trying to use radix sort to sort file contain social security and date of birth the format looks like this "###-##-####,#######.I have to apply radix sort on each fields according to command line switch. I have a radix sort that is work for int array and i am trying to modify the code for string type array but i am not sure how to accomplish this. I did a quick sort for string type by comparing strings and pivot and that is work fine however for radix sort I am not if I can do this with string type or I have to convert the string to integer. I have tried to use "atoi" to convert to integer but I am not sure how to correctly do this if I have to.
string getMax(string arr[], int n){
string max = arr[0];
for (int i = 1; i < n; i++){
if (arr[i]>max)
max = arr[i];
}
return max;
}
void countSort(string a[], int size, int k){
string *b = NULL; int *c = NULL;
b = new string[size];
c = new int[k];
for (int i = 0; i <k; i++){
c[i] = 0;
//cout << c[i] << "\n";
}
for (int j = 0; j <size; j++){
c[(a[j]/k)%10]++; //a[j] is a string
//cout << c[a[j]] << endl;
}
for (int f = 1; f <10; f++){
c[f] += c[f - 1];
}
for (int r = size - 1; r >= 0; r--){
b[c[(a[r] / k) % 10] - 1] = a[r];
c[(a[r] / k) % 10]--;
}
for (int l = 0; l < size; l++){
a[l] = b[l];
}
}
void radixSort(string b[], int r){
string max = getMax(b, r);
for (int digit = 1; max / digit > 0; digit *= 10){
countSort(b, r, digit);
}
};
I didn't try, but I think you can do radix sort for string.
Calculate the length of the longest string in the array to sort.
Do radix sort just like for integers. Do sorting using each characters in the string.
If a string is shorter than another and there is no character in the "digit", consider its value as -65536 (or a smaller value than any other characters).
UPDATE: I tested my idea and it seems working.
#include <cstdio>
#include <string>
using std::string;
size_t getMax(string arr[], int n){
size_t max = arr[0].size();
for (int i = 1; i < n; i++){
if (arr[i].size()>max)
max = arr[i].size();
}
return max;
}
void countSort(string a[], int size, size_t k){
string *b = NULL; int *c = NULL;
b = new string[size];
c = new int[257];
for (int i = 0; i <257; i++){
c[i] = 0;
//cout << c[i] << "\n";
}
for (int j = 0; j <size; j++){
c[k < a[j].size() ? (int)(unsigned char)a[j][k] + 1 : 0]++; //a[j] is a string
//cout << c[a[j]] << endl;
}
for (int f = 1; f <257; f++){
c[f] += c[f - 1];
}
for (int r = size - 1; r >= 0; r--){
b[c[k < a[r].size() ? (int)(unsigned char)a[r][k] + 1 : 0] - 1] = a[r];
c[k < a[r].size() ? (int)(unsigned char)a[r][k] + 1 : 0]--;
}
for (int l = 0; l < size; l++){
a[l] = b[l];
}
// avold memory leak
delete[] b;
delete[] c;
}
void radixSort(string b[], int r){
size_t max = getMax(b, r);
for (size_t digit = max; digit > 0; digit--){ // size_t is unsigned, so avoid using digit >= 0, which is always true
countSort(b, r, digit - 1);
}
}
int main(void) {
string data[] = {
"aaaba",
"dfjasdlifjai",
"jiifjeogiejogp",
"aabaaaa",
"gsgj",
"gerph",
"aaaaaaa",
"htjltjlrth",
"joasdjfisdjfdo",
"hthe",
"aaaaaba",
"jrykpjl",
"hkoptjltp",
"aaaaaa",
"lprrjt"
};
puts("before sorting:");
for (size_t i = 0; i < sizeof(data) / sizeof(data[0]); i++) {
printf(" %s\n", data[i].c_str());
}
radixSort(data, (int)(sizeof(data) / sizeof(data[0])));
puts("after sorting:");
for (size_t i = 0; i < sizeof(data) / sizeof(data[0]); i++) {
printf(" %s\n", data[i].c_str());
}
return 0;
}