ThoughtWorks Interview Question
Applications DevelopersCountry: India
Interview Type: In-Person
Of course, internally the compiler will create some sort of loop to do this. But what other solutions are we to offer? Of course we could copy and paste the print command 1000 times, but that's an awful solution.
I guess we could do something like print2() { print(); print(); } print4() {print2(); print2(); }... etc. to reduce the code size, but it's still not easy to adjust when you want to change 1000 to some other value.
There is no loops my friend . i an just calling constructor 1000 times..
Thanks Mukesh and Abhey.
"Of course, internally the compiler will create some sort of loop to do this."
Notice the keyword "internally". How do you think the C++ compiler achieves the initialization of the objects in the array? In the compiled code, it generates a loop to do it.
Any one has idea how we can do this in JAVA ?
Can we call such block multiple times by just mentioning the count.
@Himanshu: I'm not aware of any way to just run a static block of code a specified number of times. Some languages have features like that, but not Java, as far as I remember.
However, for this specific problem, which is a little more limited in scope, you can use the technique I outlined in one of my other comments.
public class Tester004 {
public static void main(String[] args) {
int limit=5;
char c='a';
go(0,limit,c);
}
public static void go(int i,int limit, char c) {
if (i < limit) {
System.out.println(c);
i++;
go2(i,limit,c);
}
}
public static void go2(int i,int limit, char c) {
if (i < limit) {
System.out.println(c);
i++;
go(i,limit,c);
}
}
}
In embedded scenario: Configure a timer interrupt, in the ISR keep writing the character until a counter variable reaches 1000.
In Desktop App: Use Timer class from Java Utils or equivalent API routines which give the feature of periodic execution of a function.
I could argue that this too is a loop.
There isn't a clear line between what is a loop and what isn't.
if Python, print 'a' * 1000
if C or C++,
const int BUFFER_SIZE = 1000;
char * a = (char *)malloc(BUFFER_SIZE + 1);
memset(a,'a', BUFFER_SIZE);
a[BUFFER_SIZE] = 0;
printf("%s",a);
free(a);
C# (via Lambda Linq)
char[] word = new char[10];
word = word.Select(x => x = 'a').ToArray();
Console.WriteLine(word);
Console.ReadLine();
Label and goto statement may be used for the solution.
count=0;
label:
// print here
if(++count<1000) goto label;
In C++ you could also make a constructor for a class do it, and then make an array of size 1000 of that class.
The problem with templates is that if I recall correctly, they're expanded at compile time. Meaning the compiled version of your code will have 1000 print calls, possibly bloating the code size (for 1000 it's not so bad, but what if you need 1000000?)
Exactly. So this is the right solution. No loops, recursion whatsoever!
If you do it at runtime, you will end up having some kind of a loop!
So your comment about 10^blah is irrelevant.
eh...
The right solution is to ask the interviewer to define the constraints on the problem better, and define the desired tradeoffs better.
Absent that, we can only guess what might have been wanted here. Most of the answers here are right, from a certain perspective...
A solution of a similar flavor in Java would be to create an array of characters, char[1000], call Arrays.fill (yourCharArray, 'a'), construct a new String from the char array, and then print the string.
Of course, Arrays.fill, like most other solutions here, uses a loop internally. I think that's probably going to have to be OK, because what are we to offer that doesn't?
Using setjmp and longjmp
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
int main()
{
jmp_buf env;
int val;
char a = 'c';
// first time returns 0
val = setjmp(env);
printf ("%c",a);
if (val < 999)
longjmp(env, ++val);
return 0;
}
Reproducing the comment here for your convenience:
A solution of a similar flavor in Java would be to create an array of characters, char[1000], call Arrays.fill (yourCharArray, 'a'), construct a new String from the char array, and then print the string.
Of course, Arrays.fill, like most other solutions here, uses a loop internally. I think that's probably going to have to be OK, because what are we to offer that doesn't?
Here is my solution with Java
public class A extends B{
static int m = 0;
public A()
{
}
public static void main(String args[])
{
B b = new B();
}
}
public class B {
A c;
public B()
{
A.m++;
System.out.println("e");
if(A.m < 1000)
{
c = new A();
}
}
}
Here in Ruby I'll def a method that pass in the character to be printed 1000 times:
def print1000 (a)
puts a*1000
end
#problem?
Forgot to print the character. Below is the modified code.
void main()
{
int i = 1;
char ch='v';
label1:
cout<<ch;
if( i++ <= 1000 )
goto label1;
}
May be we can write two methods, calling each other.
public void func1(String inputStr, int count) {
if ( count != 1000 ) {
System.out.println(inputStr);
count++;
func2(inputStr, count);
}
}
public void func2(String inputStr, int count) {
if ( count != 1000 ) {
System.out.println(inputStr);
count++;
func1(inputStr, count);
}
}
The initial value of count is 0.
How is this not recursion? Methods calling themselves, even indirectly, is still recursion.
public class Print
{
static int count=1;
public static void func1() {
if ( count != 1001 ) {
System.out.println("value of count"+count);
count++;
func2();
}
}
public static void func2() {
if ( count != 1001 ) {
System.out.println("value of count"+count);
count++;
func1();
}
}
public static void main(String args[])
{
func1();
}
}
gcc provieds a way to initalize an array at time of defining it. We may use this solution (look at gcc -s output for more details):
#include<stdio.h>
char a[1001]={[0 ... 999] = 'a'};
main() {
printf("%s\n", a);
return 0;
}
I wrote two classes A and B . A calls B and B calls A untill count becomes 1000. Its Ruby code.
class A
def initialize(val,count)
@val= val
@count= count
if @count <= 1000 then
puts "#{@val} in class A count= #{@count}"
@count = @count+1
B.new(@val,@count)
end
end
end
class B
def initialize(val,count)
@val= val
@count= count
if @count <= 1000 then
puts "#{@val} in class B count= #{@count}"
@count = @count+1
A.new(@val,@count)
end
end
end
puts "Enter your charector"
val= gets.chomp
count= 0
A.new(val,count)
We could employ timer callbacks for the same. Found some CPP code prints "tick" continuously until interrupted. I modified the same to print char "a" a thousand time. Please check if this will do?
#include <iostream>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost::asio;
using namespace std;
class Deadline
{
public:
Deadline(deadline_timer &timer) : t(timer) {
wait();
count = 0;
}
void timeout(const boost::system::error_code &e) {
if (e)
return;
if (count < 1000)
{
cout << "a" << endl;
}
else
{
return;
}
count++;
wait();
}
void cancel() {
t.cancel();
}
private:
void wait() {
t.expires_from_now(boost::posix_time::seconds(1)); //repeat rate here
t.async_wait(boost::bind(&Deadline::timeout, this, boost::asio::placeholders::error));
}
deadline_timer &t;
int count;
};
class CancelDeadline {
public:
CancelDeadline(Deadline &d) :dl(d) { }
void operator()() {
string cancel;
cin >> cancel;
dl.cancel();
return;
}
private:
Deadline &dl;
};
int main()
{
io_service io;
deadline_timer t(io);
Deadline d(t);
CancelDeadline cd(d);
boost::thread thr1(cd);
io.run();
return 0;
}
package learn;
import java.lang.reflect.Array;
/**
* Created by comp17 on 12-11-2014.
*/
public class PrintChars {
private int limit;
private char chr;
public PrintChars(int limit, char chr){
this.limit = limit;
this.chr = chr;
}
private void printCharsNTimes(){
String sb = new String(new char[this.limit]);
System.out.println(sb.replaceAll("", String.valueOf(this.chr)));
}
public static void main(String [] args){
PrintChars printChars = new PrintChars(10, 'M');
printChars.printCharsNTimes();
}
}
Using Java
import java.io.*;
public class A {
static int cnt=0;
public A()
{
B n=new B();
}
public static void main(String [] args)
{
A d=new A();
}
public class B{
public B(){
A c;
System.out.println("p");
cnt++;
if(cnt<1000)
c=new A();
}
}
}
It can be done using String constructor which takes a character and number of times it needs to copied.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Employee
{
public class Contact
{
public string Name { get; private set; }
public string PhoneNumber { get; private set; }
public string Address { get; private set; }
public string _All
{
get
{
return string.Format("{0}:{1}:{2}",
this.Name,
this.PhoneNumber,
this.Address).ToLower();
}
}
public Contact(string name, string phoneNumber, string address)
{
this.Name = name;
this.PhoneNumber = phoneNumber;
this.Address = address;
}
}
public class PhoneBook
{
private readonly IEnumerable<Contact> _contact;
public PhoneBook(IEnumerable<Contact> contact)
{
this._contact = contact;
}
public IEnumerable<Contact> lookForName(string name)
{
var lookup = _contact.ToLookup(nd => nd.Name);
return lookup[name];
}
public IEnumerable<Contact> lookForPhoneNumber(string phoneNumber)
{
var lookup = _contact.ToLookup(nd => nd.PhoneNumber);
return lookup[phoneNumber];
}
public IEnumerable<Contact> lookForAlphabet(char letter)
{
var lookup = _contact.ToLookup(p => Convert.ToChar(p.Name.Substring(0, 1)),
p => p);
return lookup[letter];
}
public IEnumerable<Contact> lookForAll(string anyVal)
{
var lookup = _contact.Where(p => p._All.Contains(anyVal.ToLower()));
return lookup;
}
}
class CustomComparer : IEqualityComparer<Contact>
{
}
}
public class Tests
{
[SetUp]
public void Setup()
{
}
[Test]
public void UnitTest1()
{
var numberContext = new NumberContext(100);
numberContext.OnNumberChange += OnNumberChange(numberContext);
numberContext.CurrentNumber = 1;
}
OnNumberChangeHandler OnNumberChange(NumberContext numberContext)
{
return (o, args) =>
{
if (args.Counter > numberContext.LastNumber)
return;
Console.WriteLine(numberContext.CurrentNumber);
args.Counter += 1;
numberContext.CurrentNumber = args.Counter;
};
}
}
public delegate void OnNumberChangeHandler(object source, OnNumberChangeEventArgs e);
public class NumberContext
{
public NumberContext(int lastNumber)
{
LastNumber = lastNumber;
}
public event OnNumberChangeHandler OnNumberChange;
private int currentNumber;
public int CurrentNumber
{
get { return currentNumber; }
set {
currentNumber = value;
OnNumberChange(this, new OnNumberChangeEventArgs(value));
}
}
public int LastNumber { get; set; }
public class OnNumberChangeEventArgs : EventArgs
{
public OnNumberChangeEventArgs(int counter)
{
Counter = counter;
}
public int Counter { get; set; }
}
}
public class Tests
{
[SetUp]
public void Setup()
{
}
[Test]
public void UnitTest1()
{
var numberContext = new NumberContext(100);
numberContext.OnNumberChange += OnNumberChange(numberContext);
numberContext.CurrentNumber = 1;
}
OnNumberChangeHandler OnNumberChange(NumberContext numberContext)
{
return (o, args) =>
{
if (args.Counter > numberContext.LastNumber)
return;
Console.WriteLine(numberContext.CurrentNumber);
args.Counter += 1;
numberContext.CurrentNumber = args.Counter;
};
}
}
public delegate void OnNumberChangeHandler(object source, OnNumberChangeEventArgs e);
public class NumberContext
{
public NumberContext(int lastNumber)
{
LastNumber = lastNumber;
}
public event OnNumberChangeHandler OnNumberChange;
private int currentNumber;
public int CurrentNumber
{
get { return currentNumber; }
set {
currentNumber = value;
OnNumberChange(this, new OnNumberChangeEventArgs(value));
}
}
public int LastNumber { get; set; }
public class OnNumberChangeEventArgs : EventArgs
{
public OnNumberChangeEventArgs(int counter)
{
Counter = counter;
}
public int Counter { get; set; }
}
}
We can use class.. No recursion, No loops..
- Hitesh Vaghani September 08, 2012