I need to find the smallest number formed from the same digits of a given natural number n, using arrays.
I need to find the smallest number formed from the same digits of a given natural number n, using arrays.
#include <fstream>
#include <math.h>
int *list;
bool arrange(int length){
for(int i=0;i<length;i++)
{
if(list[i]>list[i+1])
swap(list[i],list[i+1]);
}
for(int i=0;i<length;i++)cout<<"my new list contains "<<list [i]<<endl;
return true;
}
bool file(char* Filename, int length)
{
ifstream file;
file.open(Filename);
list=new int[length];
for(int i=0;i<length;i++)
{
file>>list[i];
cout<<"the list contain: "<<list[i]<<endl;
}
arrange(length);
return true;
}
Say you have the number: 251
The smallest number from those digits will be: 125
Therefore: digit1 = smallest number, digit2 = next smallest, etc.
Seperate the number into individual digits using an array. Find the smallest value and put this in the first index of a new array. Repeat this, removing the number you use each time, until you have no numbers left in the original array. Put all of the new array's values into a string and convert that to an int. This is your new number!
EDIT: You may want to use lists not an array.
EDIT EDIT: Oops got beaten too it. Ah well :)
I've found a code that works very well:
#include<iostream>
using namespace std;
int main()
{
int n,a[10],i,j;
for(i=0;i<=9;i++) a[i]=0;
cin>>n;
while(n>0)
{
a[n%10]++;
n=n/10;
}
i=1;
while(a[i]==0) i++;
n=i;
a[i]--;
for(i=0;i<=9;i++)
for(j=1;j<=a[i];j++)
n=n*10+i;
cout<<n;
return 0;
}
I think it's still difficult for me to understand why for(i=0;i<=9;i++) a[i]=0;
before cin>>n
and what is the significance of j
.
Otherwise, the code looks like you are trying to explain.
Next time, please press the code button before you paste your code.
for (i=0; i<=9; i++){}
Ever done a while loop before? Consider a loop which is while (i<=9){}
. At the end of the loop, you would have i++;
to increment the value of i
.
Basically (in a for loop): i=0
makes a new variable called i
which is set to 0
. i<=9
means that we keep looping while i
is less than or equal to 9. i++
means that we increment the value of i
once each loop.
I didn't understand why for(...) at the beginning, a has to be 0.
I didn't understand why for(...) at the beginning, a has to be 0.
Who says it has to be 0? Test it. First thing in the program just print out the array.