I've been a zone leader with DZone since 2008, and I'm crazy about community. Every day I get to work with the best that JavaScript, HTML5, Android and iOS has to offer, creating apps that truly make at difference, as principal front-end architect at Avego. James is a DZone Zone Leader and has posted 639 posts at DZone. You can read more from them at their website. View Full User Profile

Thursday Code Puzzler: Count The Ones

06.27.2012
| 4777 views |
  • submit to reddit

It's Thursday already, so time for another code puzzler. The idea is simple: solve the coding problem as efficiently as you can, in any language or framework that you find suitable.

Note: Even though there really is nothing stopping you from finding a solution to this on the internet, try to keep honest, and come up with your own answer.  It's all about the participation!

Counting Ones

Given an array of numbers, return the occurances of the number 1 in the array. So, if the array contains 1, 2, 11, 13 you would return 4 (as 11 contains two instances of 1). 

Catch up on all our previous puzzlers here

Comments

Alexey Grigorev replied on Thu, 2012/06/28 - 12:48am

countOnes = lambda s: s.count('1')
plus = lambda a, b: a + b

def count(inputList):
    counted = map(countOnes, map(str, inputList))
    return reduce(plus, counted)

print count([1, 2, 11, 13])

Chirag Visavadia replied on Thu, 2012/06/28 - 2:29am

public class CountOnes {
	public static void main(String[] args) {
		int digitToCount = 1;
		int[] numbers = { 1, 2, 11, 13, 111, 222, 333, 444, 51121, 11110 };
		int count = 0;

		for (int digit : numbers) {
			System.out.print(digit + ", ");

			do {
				// Taking and comparing remainder
				if ((digit % 10) == digitToCount)
					count++;

			} while ((digit /= 10) > 0);
		}
		System.out.println("\nCount: " + count);
	}
}

Reinhard Nägele replied on Thu, 2012/06/28 - 2:40am

def computeOnes(List numbers) {
    (numbers.join() =~ /(1)/).getCount()
}

println computeOnes([1, 2, 11, 13])

Vijay Nathani replied on Thu, 2012/06/28 - 3:13am

Groovy solution that prints 4.

Integer[] numbers =  [ 1, 2, 11, 13 ] 
println numbers.join('').count('1')

 

Thomas Mueller replied on Thu, 2012/06/28 - 3:50am in response to: Vijay Nathani

int[] x = {1, 2, 11, 13};
System.out.println(Arrays.toString(x).replaceAll("[^1]", "").length());

Oliver Michels replied on Thu, 2012/06/28 - 4:04am

My Clojure solution:

(def number '(1 2 11 13))
(println (count (re-seq #"1" (apply str numbers))))

 

Tariq Amin replied on Thu, 2012/06/28 - 11:46am

		String str = Arrays.toString(new int[]{1,2,11,13});
		int count = 0;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i)=='1') count++;
		}
		System.out.println(count);

Jason Shin replied on Thu, 2012/06/28 - 11:02pm

public class TheCounter {
	public static void main(String[] args){
		//ArrayList al = new ArrayList();
		int NUMBERS[] = {1, 12 ,31, 41, 11, 13, 15, 18, 12, 1, 1241223412, 131231231, 1231231, 1110945868, 11};
		StringBuilder sb = new StringBuilder();
		for(int i = 0; i < NUMBERS.length; i++){
			sb.append(NUMBERS[i]);
		}
		int NUM_ONE = sb.toString().replaceAll("[^1]", "").length();
		System.out.println("Number of 1 in the array: " + NUM_ONE);
	}
}

Mariusz Lotko replied on Fri, 2012/06/29 - 12:40am

Arrays.toString(1, 2, 3, 12, 11).replaceAll("[^1]", "").length()

Kevin Sapper replied on Fri, 2012/06/29 - 1:26am

Nice solution guys. I especially liked the map/reduce one ;) I've been busting my head to find a solution better than O(n). Does anyone has an idea? Is this even possible?

Jen Fleury replied on Fri, 2012/06/29 - 2:50pm

in groovy:

def myArrayList = new ArrayList([1, 2, 11, 13, 111, 0, 15, 1167111])
println myArrayList.toString().count('1')

Jen Fleury replied on Fri, 2012/06/29 - 2:52pm in response to: Jen Fleury

of course now I see mine is just like Vijay's

Ramana Tamilselvan replied on Tue, 2013/11/19 - 12:32pm

package com.code.puzzler; public class countParticularNum{ public static void main(String[] args) { int[] arr={10,121,351,441,1105}; System.out.print("Array of Values: {"); for(int i=0;i<arr.length;i++) { System.out.print(arr[i]+", "); } System.out.println("}"); int count=0; for(int j=0;j<arr.length;j++) { String str=Integer.toString(arr[j]); for(int k=0;k<str.length();k++) { if(str.charAt(k)=='1') { count++; } } } System.out.println("One Occurs at "+count+" times"); } }

Mahtab Alam replied on Thu, 2014/08/28 - 11:29pm

This is my take with Java.

class One
{
     public static void main(String args[])
	 {
	 
	    int array[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,100};
		int reminder=0;
		int count=0;
		int num=0;
		for(int i=0;i<array.length;i++)
		{
		   num=array[i];
		   while(num > 0)
		   {
		        reminder=num % 10;
				num=num / 10;
				if(reminder==1)
				{
				  count++;
				}
		   }
		
		
		}
		System.out.println("Total number of one digit is "+count);
	 
	 }


}

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.