Skip to content

Instantly share code, notes, and snippets.

@LuckyKoala LuckyKoala/6174.c
Last active Jun 18, 2018

What would you like to do?
#include <stdio.h>
#include <stdlib.h>
//------Common base------
typedef int bool;
enum { false, true };
//------Define a struct of four digit number------
typedef struct {
int thousand;
int hundred;
int ten;
int one;
} Number;
//------Exchange the value of two number------
void exchange(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
//------Fill the values of array to struct Number------
void fill(Number *num, int *arr) {
num->thousand = arr[0];
num->hundred = arr[1];
num->ten = arr[2];
num->one = arr[3];
//------Bubble Sort------
void bubbleSort(int *arr, int size, bool (*predicate)(int, int)) {
for(int i=0; i<size; i++) {
int *prev = arr+i;
for(int j=i+1; j<size; j++) {
int *current = arr+j;
if((*predicate)(*prev, *current) == true) exchange(prev, current);
//------If a is less than b, then the return value is true------
bool less(int a, int b) {
if(a<b) return true;
else return false;
//------If a is greater than or equal to b, then the return value is true------
bool greaterEqual(int a, int b) {
if(less(a,b)==true) return false;
else return true;
//------Substract two number and return the result------
int diff(Number *arr) {
int bigger = arr->thousand*1000 + arr->hundred*100 + arr->ten*10 + arr->one;
int smaller = (arr+1)->thousand*1000 + (arr+1)->hundred*100 + (arr+1)->ten*10 + (arr+1)->one;
int result = bigger-smaller;
printf("%d - %d = %d\n", bigger, smaller, result);
return result;
//------Reorder orignal number to get two number while one is biggest and other smallest------
//------ and then return the result of substraction------
int get(Number ori) {
int num[4] = {ori.thousand, ori.hundred, ori.ten,};
Number ret[2];
bubbleSort(num, 4, less);
fill(ret, num);
bubbleSort(num, 4, greaterEqual);
fill(ret+1, num);
return diff(ret);
//------Give a number to see whether it can be computed to be 6174 in limited trials------
bool compute(int num, int cnt) {
if(cnt==0) return false;
Number n;
int rem = 0;
n.thousand = num/1000;
rem = num%1000;
n.hundred = rem/100;
rem = rem%100;
n.ten = rem/10;
rem = rem%10; = rem;
if(n.thousand==n.hundred && n.hundred==n.ten && return 0;
int newNum = get(n);
if(newNum == 6174) return true;
else return compute(newNum, cnt-1);
int DEFAULT_CNT = 7;
//------Entry method------
int main(int argc, char **argv) {
if(argc<2) {
printf("No input\n");
return 0;
for(int i=1; i<argc; i++) {
printf("Result: %d\n", compute(atoi(argv[i]), DEFAULT_CNT));
return 0;
//gcc -Wall 6174.c -o 6174
//./6174 2000 1234 #To compute 2000 and 1234
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.