Skip to content

Instantly share code, notes, and snippets.

@dlresende
Last active March 20, 2021 19:51
Show Gist options
  • Save dlresende/60b4c0240ad020a323ad to your computer and use it in GitHub Desktop.
Save dlresende/60b4c0240ad020a323ad to your computer and use it in GitHub Desktop.
FooBarQix Kata

FooBarQix Kata

Write a program that prints numbers from 1 to 100, one number per line. For each printed number, use the following rules:

  1. if the number is divisible by 3 or contains 3, replace 3 by "Foo";
  2. if the number is divisible by 5 or contains 5, replace 5 by "Bar";
  3. if the number is devisible by 7 or contains 7, replace 7 by "Qix".

Example: 1 2 FooFoo 4 BarBar Foo QixQix 8 Foo Bar

More details:

  • divisors have high precedence, ex: 51 -> FooBar
  • the content is analysed in the order they appear, ex: 53 -> BarFoo
  • 13 contains 3 so we print "Foo"
  • 15 is divisible by 3 and 5 and contains 5, so we print “FooBarBar”
  • 33 contains 3 two times and is divisible by 3, so we print “FooFooFoo”
@varnit02
Copy link

package com.LinkedList;

import java.util.Arrays;

public class test1 {
public static void main(String[] args) {
foo_bar_qix(303);
}

private static void foo_bar_qix(int num) {

	String result_string = "";

	Boolean flag = false;
	if (num < 3) {
		System.out.println(num);
		return;
	}

	if (num % 3 == 0) {
		result_string += "Foo";
		flag = true;
	}

	if (num % 5 == 0) {
		result_string += "Bar";
		flag = true;
	}

	if (num % 7 == 0) {
		result_string += "Qix";
		flag = true;
	}

	if (num < 9) {
		if (!flag) {
			System.out.println(num);
			return;
		}

		if (num == 3) {
			result_string += "Foo";
		}

		if (num == 5) {
			result_string += "Bar";
		}

		if (num == 7) {
			result_string += "Qix";
		}
	}

	if (num > 9) {

		int[] digits_array = extractDigits(num);
		System.out.println(Arrays.toString(digits_array));
		for (int i = 0; i < digits_array.length; i++) {
			if (digits_array[i] == 3) {
				result_string += "Foo";
			} else if (digits_array[i] == 5) {
				result_string += "Bar";
			} else if (digits_array[i] == 7) {
				result_string += "Qix";
			} 

		}
	}
	System.out.println(result_string);
}

private static int[] extractDigits(int num) {
	int length = Integer.toString(num).length();
	int[] digit_array = new int[length];
	int i = 0;
	while (num >= 1) {
		digit_array[digit_array.length - i - 1] = num % 10;
		num = num / 10;
		i++;
	}
	return digit_array;
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment