Skip to main content

재밌는 퀴즈 몇개

웹 서핑을 하다가 우연히 Sample Interview Questions라는 페이지를 찾았는데 제목은 뭔가 이상하지만 결국은 재밌는 퀴즈들이 모여있는 페이지입니다.
오랫만에 머리를 써보자 생각하고 몇 문제 풀어보았는데 재밌네요!! ;)

앞에서부터 풀고 있는데 한번 시간되면 풀어보세요.
  1. 사각형의 케잌안에 사각형 모양의 구멍이 있습니다. 이 구멍의 크기나 각도는 어떻게 되어 있더라고 상관없습니다. 한칼에 이 남은 케잌을 정확히 이등분하려면 어떻게 잘라야 할까요?
  2. 정수로 이루어진 배열이 있습니다. 이 배열의 sub 배열중 최대값을 가지는 sub 배열을 O(N) 의 복잡도로 찾는 프로그램을 작성하세요.
    - 배열: 93 5 42 -68 -91 56 -93 5 80 92
    - 정답: [7, 9] = 5 + 80 + 92 = 177
  3. 네명의 사람이 다리의 한쪽에 있습니다. 이 다리는 한번에 최대 두명만 건널 수 있으며 건너는 사람들은 반드시 손전등을 가지고 있어야 합니다. (밤이랍니다.그리고 당근 손전등은 한개입니다.) 단 각 사람이 다리를 건너는데 걸리는 시간은 사람에 따라 다르며 두명이 건널때는 둘 중 느린 사람의 속도에 맞추어야 합니다. 각 사람의 속도가 다음과 같을 때 17분만에 모든 사람이 건널 수 있는 방법을 찾으세요.
    - 사람1: 건너는데 1분
    - 사람2: 건너는데 2분
    - 사람3: 건너는데 5분
    - 사람4: 건너는데 10분
두번째 문제의 답만 빼고는 해당 페이지에 답이 있습니다. 제가 작성한 두번째 문제의 답은 내일 올려보겠습니다. :-)


원문

  1. Given a rectangular (cuboidal for the puritans) cake with a rectangular piece removed (any size or orientation), how would you cut the remainder of the cake into two equal halves with one straight cut of a knife ?
  2. You're given an array containing both positive and negative integers and required to find the subarray with the largest sum (O(N) a la KBL). Write a routine in C for the above.
  3. There are 4 men who want to cross a bridge. They all begin on the same side. You have 17 minutes to get all of them across to the other side. It is night. There is one flashlight. A maximum of two people can cross at one time. Any party who crosses, either 1 or 2 people, must have the flashlight with them. The flashlight must be walked back and forth, it cannot be thrown, etc. Each man walks at a different speed. A pair must walk together at the rate of the slower mans pace.
    - Man 1:1 minute to cross
    - Man 2: 2 minutes to cross
    - Man 3: 5 minutes to cross
    - Man 4: 10 minutes to cross

2번 정답

제가 C++로 작성해봤습니다. 더 간단한 방법이 있을지도 모르겠습니다. :-)

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <limits>
#include <boost/lambda.hpp>
#include <boost/bind.hpp>

using namespace std;
using namespace boost::lambda;

int main()
{
  srand(time(0));

  const int SIZE = 10;

  vector<int> data(SIZE);

  // use random sequence
  for_each(data.begin(), data.end(), _1 += bind(rand) % 200 - 100);

  // use hand-made test sequence
  /*
  //istringstream test("-38 66 -49 -38 78 84 49 -83 -88 32"); // [4, 6] = 211
  //istringstream test("2 -5 3 7 -9 5 3 8 -20 10"); // [2, 7] = 17
  istringstream test("93 5 42 -68 -91 56 -93 5 80 92"); // [7, 9] = 177
  for_each(data.begin(), data.end(), test >> _1);
  */

  for_each(data.begin(), data.end(), cout << _1 << ' ');
  cout << '\n';

  int end = 0;
  int maxval = data[0];
  int curr = data[0];

  for (int i = 1; i < SIZE; ++i) {
    curr += data[i];
    if (curr < data[i]) {
      curr = data[i];
    }
    if (maxval < curr) {
      maxval = curr;
      end = i;
    }
  }

  curr = maxval;
  int start = 0;
  for (start = end; curr != 0; --start) {
    curr -= data[start];
  }
  ++start;

  cout << "[" << start << ", " << end << "] = " << maxval << endl;
}

Comments

  1. 트랙백이 안걸려서 링크 올려드립니다.

    http://freesearch.pe.kr/606

    ReplyDelete

Post a Comment

Popular posts from this blog

CodeHighlighter plugin test page.

This post is for testing CodeHighlighter plugin which uses GeSHi as a fontifier engine. ((Those code blocks are acquired from Google Code Search .)) ((For more supported languages, go CodeHighlighter plugin or GeSHi homepage.)) C++ (<pre lang="cpp" lineno="1">) class nsScannerBufferList { public: /** * Buffer objects are directly followed by a data segment. The start * of the data segment is determined by increment the |this| pointer * by 1 unit. */ class Buffer : public PRCList { public: Buffer() { ++index_; } PHP (<pre lang="php" lineno="4">) for ($i = 0; $i $value = ord( $utf8_string[ $i ] ); if ( $value < 128 ) { // ASCII $unicode .= chr($value); } else { if ( count( $values ) == 0 ) { $num_octets = ( $value } $values[] = $value; Lisp (<pre lang="lisp">) ;;; Assignment (define-caller-pattern setq ((:star var fo...

C++ of the Day #43 - SQLite3 C++ wrapper #1

The Definitive Guide to SQLite 를 읽다가 공부 겸 해서 C++ wrapper를 만들어 보았습니다. 최대한 C++ 냄새(?)가 나도록 만들어 보았습니다. :-) ((SQLite는 복잡한 관리가 필요없이 사용가능한, 파일이나 메모리 기반의, 라이브러리로 제공되는, 약 250kb 용량의, 대부분의 SQL92문을 지원하는, open source RDB입니다.)) 이 wrapper를 사용하기 위해서는 (당연하게도!) sqlite3 와 (당연하게도?) boost 라이브러리가 필요합니다. 사용 예들을 살펴보는 것으로 설명을 대신합니다. 이번 글에서는 다음과 같은 contacts 테이블이 test.db에 존재한다고 가정합니다. CREATE TABLE contacts ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, phone TEXT NOT NULL, UNIQUE(name, phone) ); Command 먼저 test.db 파일을 사용하기 위해 다음과 같이 파일 이름을 주어 connection 객체를 생성합니다. 생성과 동시에 test.db와 연결이 이루어집니다. ((생성자외에 open() 함수를 사용할 수도 있습니다.)) sqlite3pp::connection conn("test.db"); 다음은 contacts 테이블에 정보를 추가하는 가장 간단한 방법입니다. connection 클래스에서 제공하는 execute 함수를 사용합니다. ((executef 함수를 사용하면 printf와 같은 문법을 사용하여 query문을 작성할 수 있습니다.)) conn.execute("INSERT INTO contacts (name, phone) VALUES ('user', '1234')"); 위와 동일한 작업을 parameterized query를 사용하여 할 수도 있습니다. ((step()함수가 실제 query문을 수행하는 함수입니다. ...

Textiler plugin test page

This post is for testing Textiler plugin . This plugin uses Textile engine (version 2.0.0). The sample text is come from Textile test page. (Note that the result will be vary according to your CSS options.) Supported wiki syntax Rendering result h2{color:green}. This is a title h3. This is a subhead p{color:red}. This is some text of dubious character. Isn't the use of "quotes" just lazy writing -- and theft of 'intellectual property' besides? I think the time has come to see a block quote. bq[fr]. This is a block quote. I'll admit it's not the most exciting block quote ever devised. Simple list: #{color:blue} one # two # three Multi-level list: # one ## aye ## bee ## see # two ## x ## y # three Mixed list: * Point one * Point two ## Step 1 ## Step 2 ## Step 3 * Point three ** Sub point 1 ** Sub point 2 Well, that went well. How about we insert an <a href="/" title="watch out">old-fashioned hypertext link</a>? Will the quo...